1:http: //i.stack.imgur.com/WYniI.png
我已经编写了在我的应用程序中显示选项卡菜单的代码。它工作正常,但在某些手机选项卡中不显示文本和图标,如附图所示。我正在使用片段。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHelper tabHelper = getTabHelper();
CompatTab menuTab = tabHelper.newTab("menu").setText(R.string.tab_section1).setIcon(
R.drawable.home_icon).setTabListener(
new InstantiatingTabListener(this, MenuFragment.class));
tabHelper.addTab(menuTab);
经过大量分类后,我发现下面的代码有问题
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//nothing xml written for menu
}
所以我尝试添加以下代码
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menufav:
Intent menuintent = new Intent(this, FavouritesFragment.class);
startActivity(menuintent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
但由于它是片段,我们不能使用意图。它抛出铸造错误。
现在我该如何解决这个问题?我有下面的点击监听器类。我想利用它。
public static class InstantiatingTabListener implements CompatTabListener {
private final TabCompatActivity mActivity;
private final Class mClass;
/**
* Constructor used each time a new tab is created.
*
* @param activity The host Activity, used to instantiate the fragment
* @param cls The class representing the fragment to instantiate
*/
public InstantiatingTabListener(TabCompatActivity activity, Class<? extends Fragment> cls) {
mActivity = activity;
mClass = cls;
}
/* The following are each of the ActionBar.TabListener callbacks */
@Override
public void onTabSelected(CompatTab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
Fragment fragment = tab.getFragment();
if (fragment == null) {
// If not, instantiate and add it to the activity
fragment = Fragment.instantiate(mActivity, mClass.getName());
tab.setFragment(fragment);
ft.add(android.R.id.tabcontent, fragment, tab.getTag());
} else {
// If it exists, simply attach it in order to show it
ft.attach(fragment);
}
}
@Override
public void onTabUnselected(CompatTab tab, FragmentTransaction ft) {
Fragment fragment = tab.getFragment();
if (fragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(fragment);
}
}
@Override
public void onTabReselected(CompatTab tab, FragmentTransaction ft) {
}
}