android - 更改基本导航抽屉模板中的 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
(你好世界)仍然显示。
解决方案
也许你应该尝试framelayout
在你的content_main
xml 文件中创建一个。然后将新片段加载到框架布局中。这就像为新片段创建一个框架。然后像这样加载它:
transaction.add(R.id.yourframelayoutid, new Drawer_Emergencies()).commit();
推荐阅读
- javascript - javascript: `Date()` 和 `new Date()`
- regex - 正则表达式在文件中搜索一组括号,其中包含八个字符,全为 1 或 0,至少有一个 1?
- graphql - Absinthe Graphql 嵌套查询安全性
- c - C - 将带有重复分隔符字符的字符串拆分为 2 个子字符串
- java - 无法通过构造函数自动装配
- java - 为什么 ScheduledExecutorService 使用“新”关键字导致内存泄漏
- google-maps - 在服务器端渲染谷歌地图
- c# - C# 将数据重定向到已经运行的控制台 exe
- python - Xlsxwriter,只格式化一些单元格,而不是整行或整列?
- java - 在java中将元素转换为对象不起作用