当Activity在多个片段之间切换时,如何以“干净”和正确的方式实现选项和上下文菜单?
这里使用NavigationDrawer的示例代码:
public class MainActivity extends Activity implements OnFragmentInteractionListener {
...
@Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragmentManager.beginTransaction().replace(R.id.container, Fragment1.newInstance(null, null)).commit();
break;
case 1:
fragmentManager.beginTransaction().replace(R.id.container, Fragment2.newInstance(null, null)).commit();
break;
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// ???
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
// ???
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
// ???
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//???
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// ???
return super.onContextItemSelected(item);
}
@Override
public void onFragmentInteraction(String id) {
// ???
}
}
public class Fragment1 extends Fragment {
// ???
// option menu item A
// listView1 context menu item X
}
public class Fragment2 extends Fragment {
// ???
// option menu item B
// listView 2 context menu item Y
}
也许我走错了路。我有点困惑......
答案 0 :(得分:2)
据我所知,你想为每个片段设置不同的菜单?您可以为每个片段指定一个菜单,它只会显示该片段何时附加到Activity。以下代码都属于片段。
你必须告诉片段它有一个选项菜单:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
然后为这个片段的菜单充气:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.about, menu);
}
然后在点击菜单时处理菜单中的每个项目:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle menu item click here
return super.onOptionsItemSelected(item);
}
您还可以指定"全球"活动中的菜单和那些菜单项以及当前片段的菜单项都会显示。