我得到了這個代碼,用於在Android Java中使用導航抽屜來更改碎片。只需遵循Google官方開發者帖子和其他頁面,但它仍然無效。只是頁面的標題改變而不是佈局。請告訴我爲什麼,我不會問我是否嘗試過很多並閱讀其他帖子。更改片段。爲什麼它不起作用
因此,這裏是我的代碼: 在任務列表的Java
public class TaskList extends Fragment {
View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main_tasklist, container, false);
return super.onCreateView(inflater, container, savedInstanceState);
}
MainActivity的Java文件
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment f = null;
Class fClass = null;
// Tasklist
if (id == R.id.nav_drawer_main_tasklist) {
fClass = TaskList.class;
}
try{
f=(Fragment) fClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_main,f).commit();
item.setChecked(true);
setTitle(item.getTitle());
// Drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerlayout_main);
drawer.closeDrawer(GravityCompat.START
);
在任務列表XML文件
<?xml version="1.0" encoding="utf-8"?>
<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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="***">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_main_createtask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|end"
android:onClick="fab_main_createtask_onClick"
app:srcCompat="@drawable/ic_add_white_24dp"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
</LinearLayout>
</RelativeLayout>
你觸發了默認onCreateView導致什麼 – Remario
視圖不能不能爲空,這樣標註是錯誤的。 – Remario