我已經發現了很多關於此問題的內容,但我確實無法解決我的問題。我在這裏花了幾個小時,但沒有。無法從導航抽屜項目加載片段
我有一個使用Android Studio 2.1.1模板製作的導航抽屜活動。當然,我想要改變我的應用的視圖,當我點擊菜單中的一個項目時,顯示不同的碎片。這是我在MainActivity代碼:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
new gaussFragment();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
當我點擊抽屜式導航欄(在一個id爲R.id.nav_camera
)的第一個項目,我可以看到的烤麪包,但新的片段沒有出現。我使用這個代碼在gaussFragment()
:
public class gaussFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_gauss, container, false);
}
}
當然,你可以看到here的fragment_gauss.xml是有這個代碼,它的相對佈局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.androidhive.tabsswipexx.gaussFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
我怎麼能解決這個問題?
content_main是我在應用程序啓動時看到的第一個東西。我應該嘗試添加一些像
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
並以某種方式加載我的碎片?
好選擇每次都被顯示出來,你犯了一個新的片段d它立即被垃圾收集......你需要一個FragmentTransaction來將它加載到FrameLayout中 –
我怎麼能編碼它? –
看看[文檔](https://developer.android.com/training/basics/fragments/fragment-ui.html)是否有幫助,然後再回答問題。 –