我的活动已扩展到AppCompatActivity。我也成功安装了一个抽屉。现在,当我基本上在Fragment上进行事务处理时,它将使用begintransaction。但是我在Unreachable statement
上收到此错误消息android.app.FragmentManager fragmentManager = getFragmentManager();
,并且我还尝试了android.support.v4.app软件包,它还说这已过时。
在我的抽屉导航onClickListener
我有这个
`
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
android.app.Fragment objFragment = null;
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.dhome:
objFragment = new panel();
mCurrentSelectedPosition = 0;
return true;
case R.id.dsetting:
mCurrentSelectedPosition = 1;
return true;
case R.id.dlogout:
mCurrentSelectedPosition = 2;
return true;
default:
return true;
}
// update the main content by replacing fragments
if(objFragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
}
});`
在我的布局中
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
>
<FrameLayout android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"/>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#d9d8d8"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer" />
</android.support.v4.widget.DrawerLayout>
最佳答案
用这个:
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.dhome:
objFragment = new panel();
mCurrentSelectedPosition = 0;
break;
case R.id.dsetting:
mCurrentSelectedPosition = 1;
break;
case R.id.dlogout:
mCurrentSelectedPosition = 2;
break;
}
// update the main content by replacing fragments
if(objFragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
return true;
}
您先前的代码未考虑用户与
actionbar
的交互方式(单击任何项目),return true;
将始终在到达片段事务代码之前执行。关于java - 在Android中的FrameLayout上添加 fragment ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34345484/