Board logo

標題: Android App - Menu [打印本頁]

作者: admin    時間: 2012-6-22 23:01     標題: Android App - Menu

在 res 內增添一個資料夾 menu, 新增 menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/txtConfig"
        android:title="設定" />
    <item android:id="@+id/txtLogin"
        android:title="登入系統" />
</menu>


在 Activity JAVA 檔內加入
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.viewtest1:
                Intent i = new Intent(DynamiclistviewActivity.this, ConfigActivity.class);
                i.putExtra("Value1",value1);
                i.putExtra("Value2",value2);
                i.putExtra("Value3",value3);
                i.putExtra("Value4",value4);     
                i.putExtra("Value5",value5);
            
// Set the request code to any code you like, you can identify the
            
// callback via this code
                startActivityForResult(i, REQUEST_CODE);
                break;
            case R.id.viewtest2:  
                Intent i2 = new Intent(DynamiclistviewActivity.this, loginActivity.class);
                i2.putExtra("Value1","dummy");
                startActivityForResult(i2, REQUEST_CODE2);
                break;
        }   
         
return true;
    }

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

    @Override
    public boolean onPrepareOptionsMenu (Menu menu) {
        if (loginpass)  // loginpass is a boolean that will be changed in other part of the program
            menu.getItem(1).setEnabled(false);
        return true;
    }




歡迎光臨 How2Do (http://forum.how2do.com.hk/) Powered by Discuz! 7.2