我有一个日历应用程序。我正在使用ActionBarSherlock和Tabs。我还在Action Bar中实现了Options Menus。我希望操作栏中的一个菜单项在选择选项卡时表现不同。
如何在onOptionsItemSelected(MenuItem item)
方法中获取标签位置,以便我可以相应地编码菜单项?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab Tab1 = bar.newTab();
ActionBar.Tab Tab2 = bar.newTab();
Tab1.setText("Tab1");
Tab2.setText("Tab2");
Tab1.setTabListener(new MyTabListener());
Tab2.setTabListener(new MyTabListener());
bar.addTab(Tab1);
bar.addTab(Tab2);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
newActivity = new Intent(this, Main.class);
newActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(newActivity);
return true;
case R.id.menu_today_date:
//if condition here based on tabs selected
CalendarFragment frag = new CalendarFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(android.R.id.content, frag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
return true;
case R.id.menu_prefs:
newActivity = new Intent(this, Settings.class);
startActivityForResult(newActivity, requestCode);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class MyTabListener implements ActionBar.TabListener
{
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
我无法获得标签位置,但这就是我最终做到的方式:
private int tabSelected = 0;
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
tabSelected = 0;
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else
{
tabSelected = 1;
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId())
case R.id.menu_today_date:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (tabSelected == 0){
CalendarFragment frag = new CalendarFragment();
ft.replace(android.R.id.content, frag);
}
else {
ConverterFragment frag = new ConverterFragment();
ft.replace(android.R.id.content, frag);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
default:
return super.onOptionsItemSelected(item);
}
}