问题描述
我为工具栏创建了一个 XML 布局,并将样式更改为无操作栏。
但是该工具栏有两个问题
-
工具栏中的文本视图消失
-
工具栏有边距开始,这与父级不匹配 那么我应该如何解决这些问题呢? 这是工具栏 XML:
<?xml version="1.0" encoding="utf-8"?> <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="@color/white" android:elevation="16dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/txt_toolbar" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_margin="8dp" android:textColor="@color/black" android:textSize="22sp" tools:text="@string/app_name" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.appcompat.widget.Toolbar>
这是主要活动 XML 代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是android studio中Design view的图片
这是模拟器中的应用图片
如您所见,片段中的 Texview 也存在问题,其位置不正确,并且工具栏中的 textview 消失 那么我应该如何解决这个问题?
解决方法
您的问题的根源是 tools:text="@string/app_name"
并且如 official docs
Android Studio 支持 tools 命名空间中的各种 XML 属性,这些属性启用设计时功能(例如在片段中显示哪种布局)或编译时行为(例如将哪种收缩模式应用于您的 XML 资源) .当您构建应用时,构建工具会删除这些属性,因此不会影响您的 APK 大小或运行时行为。
在构建应用程序时从 XML 中删除了任何 toolsNs
属性,在您的情况下,这就是为什么您没有看到任何文本,而是使用 androidNs
因此请在您的 textview
android:text="@string/app_name"