1. 程式人生 > >Android開發手機選單(menu)按鍵的自定義

Android開發手機選單(menu)按鍵的自定義

預設按下選單鍵顯示只有一個item,就是settings

1.新增item

開啟res\menu\main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.mmanager.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
    <item                                         //新新增的item
        android:id="@+id/test"
        android:orderInCategory="1"
        android:title="test"
        />


</menu>

2.為新新增的item新增事件處理

在相應的activity.java中新增處理

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        else if(id==R.id.test)
        {
            System.out.println("按了test");
            return true;
        }


        return super.onOptionsItemSelected(item);
    }