不使用 TabHostFragment 显示导航抽屉
Not displaying navigation drawer with TabHostFragment
几天前我在我的 NavigationDrawerMenu
中实现了 TabHostFragment,问题是当我尝试打开 NavigationDrawer
它没有。
我的应用程序没有崩溃,但它没有打开 NavigationDrawer
,我不知道我错过了什么。我猜问题出在 setContentView()
,因为我使用另一个布局来使用我的 TabHostFragment
,我试图在我的 activity_main 中实现这个 TabHostFragment
,但我没有知道怎么说才对。
这是我的 MainActivity.class
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// saber si esta abierto
public boolean mDrawerOpened;
// nav drawer title
private CharSequence mDrawerTitle;
private FragmentTabHost mTabHost;
// used to store app title
private CharSequence mTitle;
//para ponerlo visible
public MenuItem mi;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
//AyudaSugerencias
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(
Html.fromHtml("<font color='ffffff'>"
+ mTitle + "</font>"));
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
mDrawerOpened = false;
syncState();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(
Html.fromHtml("<font color='ffffff'>"
+ mDrawerTitle + "</font>"));
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
mDrawerOpened = true;
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = null;
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.ofertasRefresh:
return true;
case R.id.menu_search:
return true;
case R.id.newOffer:
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
if (mDrawerOpened) {
menu.removeItem(R.id.ofertasRefresh);
menu.removeItem(R.id.menu_search);
menu.removeItem(R.id.newOffer);
}
if (!mDrawerOpened) {
menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle);
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
//Fragment fragment = null; ---Removed for test, because if I don't remove this line couldn't execute the app because fragment can not call a FragmentActivity....
if(position == 0){
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
setContentView(R.layout.tabhost);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
RecomendacionesFragment.class, null);
}
else
{
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 1:
fragment = new RecomendacionesFragment();
break;
case 2:
fragment = new LocalizacionFragment();
break;
case 3:
fragment = new ListaProductosFragment();
break;
case 4:
fragment = new ConfiguracionFragment();
break;
case 5:
fragment = new AyudaSugerenciasFragment();
break;
case 6:
fragment = new AyudaSugerencias();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
现在我要解释代码...
我认为我做错的是 setContentView(R.layout.tabhost);
,因为我替换了旧布局(我用另一个布局获得了 NavigationDrawer,我不再调用它了), 也许这不是问题,但我想这是唯一的解决方案...
此外,如果我在 displayView()
上输入数字 3,它会正确打开,但是当我尝试转到第一个时,它会崩溃。
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
编辑
activity_main.xml(我有我的导航抽屉)
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
tabhost.xml(我的标签在哪里)
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="@android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
编辑LOGCAT错误
03-04 16:53:05.708 2232-2232/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 2232
java.lang.IllegalStateException: No tab known for tag null
at android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.java:330)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:280)
at android.view.View.dispatchAttachedToWindow(View.java:13406)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2707)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2714)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3919)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3678)
at android.view.ViewGroup.addView(ViewGroup.java:3654)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:958)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:454)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
像这样创建一个名为 MyTabHostFragment
的新 Fragment
class:
public class MyTabHostFragment extends Fragment{
public MyTabHostFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mTabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
RecomendacionesFragment.class, null);
}
}
现在在您的 MainActivity
中,像这样修改您的 displayView()
方法:
private void displayView(int position) {
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MyTabHostFragment();
break;
case 1:
fragment = new RecomendacionesFragment();
break;
case 2:
fragment = new LocalizacionFragment();
break;
case 3:
fragment = new ListaProductosFragment();
break;
case 4:
fragment = new ConfiguracionFragment();
break;
case 5:
fragment = new AyudaSugerenciasFragment();
break;
case 6:
fragment = new AyudaSugerencias();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
并确保在 MainActivity
的 onCreate()
方法中有
setContentView(R.layout.activity_main);
而不是
setContentView(R.layout.tabhost);
试试这个。这应该有效。
编辑:
发布的错误中的崩溃是由于 Android 框架本身的错误。此错误已记录在案 here, here and here。我仍在寻找合适的解决方法。
几天前我在我的 NavigationDrawerMenu
中实现了 TabHostFragment,问题是当我尝试打开 NavigationDrawer
它没有。
我的应用程序没有崩溃,但它没有打开 NavigationDrawer
,我不知道我错过了什么。我猜问题出在 setContentView()
,因为我使用另一个布局来使用我的 TabHostFragment
,我试图在我的 activity_main 中实现这个 TabHostFragment
,但我没有知道怎么说才对。
这是我的 MainActivity.class
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// saber si esta abierto
public boolean mDrawerOpened;
// nav drawer title
private CharSequence mDrawerTitle;
private FragmentTabHost mTabHost;
// used to store app title
private CharSequence mTitle;
//para ponerlo visible
public MenuItem mi;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
//AyudaSugerencias
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(
Html.fromHtml("<font color='ffffff'>"
+ mTitle + "</font>"));
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
mDrawerOpened = false;
syncState();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(
Html.fromHtml("<font color='ffffff'>"
+ mDrawerTitle + "</font>"));
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
mDrawerOpened = true;
syncState();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = null;
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.ofertasRefresh:
return true;
case R.id.menu_search:
return true;
case R.id.newOffer:
getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
if (mDrawerOpened) {
menu.removeItem(R.id.ofertasRefresh);
menu.removeItem(R.id.menu_search);
menu.removeItem(R.id.newOffer);
}
if (!mDrawerOpened) {
menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle);
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
//Fragment fragment = null; ---Removed for test, because if I don't remove this line couldn't execute the app because fragment can not call a FragmentActivity....
if(position == 0){
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
setContentView(R.layout.tabhost);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
RecomendacionesFragment.class, null);
}
else
{
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 1:
fragment = new RecomendacionesFragment();
break;
case 2:
fragment = new LocalizacionFragment();
break;
case 3:
fragment = new ListaProductosFragment();
break;
case 4:
fragment = new ConfiguracionFragment();
break;
case 5:
fragment = new AyudaSugerenciasFragment();
break;
case 6:
fragment = new AyudaSugerencias();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
现在我要解释代码...
我认为我做错的是 setContentView(R.layout.tabhost);
,因为我替换了旧布局(我用另一个布局获得了 NavigationDrawer,我不再调用它了), 也许这不是问题,但我想这是唯一的解决方案...
此外,如果我在 displayView()
上输入数字 3,它会正确打开,但是当我尝试转到第一个时,它会崩溃。
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
编辑
activity_main.xml(我有我的导航抽屉)
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
tabhost.xml(我的标签在哪里)
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="@android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
编辑LOGCAT错误
03-04 16:53:05.708 2232-2232/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 2232
java.lang.IllegalStateException: No tab known for tag null
at android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.java:330)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:280)
at android.view.View.dispatchAttachedToWindow(View.java:13406)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2707)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2714)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3919)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3678)
at android.view.ViewGroup.addView(ViewGroup.java:3654)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:958)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:454)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
像这样创建一个名为 MyTabHostFragment
的新 Fragment
class:
public class MyTabHostFragment extends Fragment{
public MyTabHostFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mTabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
MisOfertasFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
RecomendacionesFragment.class, null);
}
}
现在在您的 MainActivity
中,像这样修改您的 displayView()
方法:
private void displayView(int position) {
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MyTabHostFragment();
break;
case 1:
fragment = new RecomendacionesFragment();
break;
case 2:
fragment = new LocalizacionFragment();
break;
case 3:
fragment = new ListaProductosFragment();
break;
case 4:
fragment = new ConfiguracionFragment();
break;
case 5:
fragment = new AyudaSugerenciasFragment();
break;
case 6:
fragment = new AyudaSugerencias();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
并确保在 MainActivity
的 onCreate()
方法中有
setContentView(R.layout.activity_main);
而不是
setContentView(R.layout.tabhost);
试试这个。这应该有效。
编辑:
发布的错误中的崩溃是由于 Android 框架本身的错误。此错误已记录在案 here, here and here。我仍在寻找合适的解决方法。