我很难搞清楚为什么我的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">
其余代码由android studio自动生成。
这是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但没有任何反应,即使注册了正确的点击。
实际上你的代码是有效的,但问题是你有blank
布局,因为片段布局的背景默认是透明的,你看不到变化。将背景颜色放在片段(LinearLayout
)的根布局上,例如:android:background="@android:color/white"
,您将看到fragement replacement。