我的 Android 应用中有一个带有片段的 ViewPager。我想根据 ViewPager 的片段显示操作栏菜单项。我已经阅读了一些关于此的问题,但我找不到正确的解决方案。我的 ViewPager 的代码是这样的:
public class My_Activity extends ActionBarActivity {
private ViewPager mViewPager;
String idioma;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_main);
ActionBar actionBar = getSupportActionBar(); // || getActionBar();
actionBar.setIcon(getResources().getDrawable(R.drawable.navbar_logo));
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC3333")));
actionBar.setTitle("Hello");
mViewPager = (ViewPager) findViewById(R.id.viewpager);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerTabStrip);
pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.blanco));
Title_Liga_Adapter titleAdapter = new Title_Liga_Adapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(0);
getSupportActionBar().setIcon(R.drawable.navbar_logo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mViewPager.getCurrentItem() == 4) {
getMenuInflater().inflate(R.menu.menu_comunidad,
menu);
} else {
}
return true;
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search)
.setVisible(true);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
this.finish();
return true;
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
我希望当 CurrentItem 为 4 时,例如显示菜单项图标。