我已经发现了很多关于此问题的内容,但我确实无法解决我的问题。我在这里花了几个小时,但没有。无法从导航抽屉项目加载片段
我有一个使用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)是否有帮助,然后再回答问题。 –