首页 > 解决方案 > 更改基本导航抽屉模板中的 content_main XML

问题描述

我对 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(你好世界)仍然显示。

目前的结果

标签: androidandroid-studio

解决方案


也许你应该尝试framelayout在你的content_mainxml 文件中创建一个。然后将新片段加载到框架布局中。这就像为新片段创建一个框架。然后像这样加载它:

transaction.add(R.id.yourframelayoutid, new Drawer_Emergencies()).commit();

推荐阅读