我看过类似的问题,并尝试了一些东西,但没有一个工作。我有一个MainActivity
,其布局包含导航抽屉片段和FrameLayout
,我用它来替换我的片段。当我点击导航抽屉片段上的一个项目时,我想要替换FrameLayout
中的第一个片段。问题在于替换操作之后,我的碎片出现在旧碎片的顶部,旧碎片未被移除。Android片段替换放在顶部的片段,不会删除旧片段
下面是用于将第一片段代码时MainActivity
启动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OptionsFragment mFragment = new OptionsFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, new OptionsFragment(), OPTIONS_TAG).commit();
这是发生在NavigationDrawerFragment
文件替换操作:
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
fragment = getFragmentManager().findFragmentByTag(MainActivity.OPTIONS_TAG);
if(fragment != null)
getFragmentManager().beginTransaction().remove(fragment).commit();
switch (position) {
case 0:
fragment = getFragmentManager().findFragmentByTag(MainActivity.LOGIN_TAG);
if (fragment == null) {
fragment = new LoginFragment();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, MainActivity.LOGIN_TAG).commit();
closeDrawer();
break;
}
}
这里是XML布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_activity">
<include
android:id="@+id/toolbar_actionbar"
layout="@layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar_actionbar">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="@+id/fragment_drawer"
android:name="com.kristmiha.myportal2.NavigationDrawerFragment"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="@layout/fragment_navigation_drawer"
tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
我猜你是混合正规'Fragment'类和支持'Fragment'类,所以'FragmentManager'你得到'NavigationDrawerFragment'不支持'FragmentManager',因此不会删除'OptionsFragment',因为它不管理它。你在'NavigationDrawerFragment'中导入了哪个'Fragment'类? –
@MikeM。确实如此。我在'NavigationDrawerFragment'类中扩展'Fragment'而不是'FragmentActivity'。有没有办法从'MainActivity'访问支持'Fragment'?我正在使用我在互联网上为导航抽屉找到的一段代码,并且扩展到'FragmentActivity'会给我其他错误。 – user3484582
不,你确实希望它扩展'Fragment',只要确保它是'android.support.v4.app.Fragment',而不是'android.app.Fragment'。检查你的'import'语句。 –