我很难弄清楚为什么我的FragmentManager不能工作。
我正在使用Android工作室模板进行导航抽屉活动。最让人困惑的是,我在另一个应用程序中有完全相同的代码,而且它运行得很好。
以下是代码:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.nav_camera:
fragment = new MyFragment();
Log.i("ID", String.valueOf(id));
break;
case R.id.nav_gallery:
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main, fragment)
.commit();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}现在,当我单击nav_camera时,它会很好地记录单击,但是没有发生任何其他事情,片段不会被替换。没有错误,没有异常,只是同一个屏幕一遍又一遍。
片段代码,这里没有什么只是测试:
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}片段布局,只是一个空白:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
其余代码由安道尔工作室自动生成。
下面是content_main,我试图用fm替换它:
<LinearLayout 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/content_main"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.goran.mymoviedb.movies.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
它应该用一个空白的nav_camera来代替布局,但是即使注册了正确的单击,也不会发生任何事情。
发布于 2017-12-22 19:27:50
实际上,您的代码正在工作,但问题是您有blank布局,而且由于片段布局的背景在默认情况下是透明的,所以您无法看到更改。将背景颜色放置在片段的根布局(LinearLayout)上,例如:android:background="@android:color/white",您将看到碎片替换。
https://stackoverflow.com/questions/47945601
复制相似问题