我正在开发一个包含3个标签/片段的应用。但是我想为每个标签设置不同的操作栏。我怎么能这样做?
这是我到目前为止所尝试的: 的 FragmentActivity
// Tab titles
private String[] tabs = { "Settings", "Company", "Receipt" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.systemsettings_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab arg0, android.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.systemsettings_menu, menu);
final MenuItem itemAdd;
itemAdd = menu.findItem(R.id.save);
itemAdd.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
但是这并没有达到我的要求,它只显示systemsettings_menu。你有什么想法怎么做?我很乐意感谢你的帮助。感谢。
答案 0 :(得分:3)
每个片段可以单独声明其菜单项,框架将基于这些构建操作栏。您应该:而不是覆盖活动的onCreateOptionsMenu(),而不是:
这应该足以满足您的目的。
有关示例,请参阅https://www.grokkingandroid.com/adding-action-items-from-within-fragments/