2013-04-13 43 views
0

我有導航菜單項。目前我在onCreateOptionsMenu中手動創建它:如何使用xml創建導航菜單項

public boolean onCreateOptionsMenu(Menu menu) { 
    mLocations = getResources().getStringArray(R.array.locations); 
    Context context = getSupportActionBar().getThemedContext(); 
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
    context, R.array.locations, R.layout.sherlock_spinner_item); 
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); 
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 
    getSupportActionBar().setListNavigationCallbacks(list, this); 
} 

有沒有一種方法可以在XML中定義它?

回答

0

你需要做兩件事:一個是設置xml,第二個是膨脹它。這裏是main.xml中

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

<item 
    android:id="@+id/action_settings" 
    android:orderInCategory="100" 
    android:showAsAction="never" 
    android:title="@string/action_settings"/> 

<item 
    android:id="@+id/exit" 
    android:orderInCategory="200" 
    android:showAsAction="never" 
    android:title="@string/exit"/> 

</menu> 

然後,膨脹的主要活動的XML:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getSupportMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

如果您使用的片段應該是這個樣子:

@Override 
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    inflater.inflate(R.menu.fragment, menu); 
} 

當然還有ha有一個匹配的fragment.xml來配合它。

祝你好運!