【发布时间】:2018-12-13 12:44:46
【问题描述】:
我真的是 android studio 的新手,并且遇到了一个非常基本的问题。 我看过一些关于这个问题的帖子,但没有一个能真正解决我的问题。
问题: 如何更改 NavigationDrawer 模板中的片段?模板提供了一个环境,其中所谓的 content_main.xml 应该被更改为另一个片段。我不知道如何完成这个
我尝试了什么:由于我无法更改 content_main.xml,我更改了整个 xml,其中包括 content_main.xml。简单看一下我的代码就更容易理解了。
模板 app_bar_main.xml 设置片段的外观并包含 content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/content_main_frame"
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"
tools:context=".MainActivity"
tools:showIn="@layout/app_bar_main"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<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" />
</FrameLayout>
在导航抽屉 main_activity 中,我像这样更改我的片段:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (id == ..) {
} else if (id == R.id.nav_emergencies) {
transaction.replace(R.id.content_main_frame, new Drawer_Emergencies());
transaction.addToBackStack(null);
transaction.commit();
}}
您可能会看到该事务替换了整个 app_bar_main,但我认为我应该只更改 app_bar_main.xml 中包含的 content_main.xml。我该如何完成?
当我实施裘德的建议时,我得到了更新的结果。片段在正确的位置,但不知何故,content_main_frame.xml(hello world)仍然显示。
【问题讨论】: