为什么不显示androidx.appcompat.widget.Toolbar



我创建了一个 BaseActivity 来创建一个工具栏,并在 onCreate(( 中设置支持操作栏((。但是它的子类不能显示工具栏。为什么?

部分样式.xml:

<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">

AndroidManifest的一部分.xml:

<application
android:name=".utils.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

布局文件common_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/comm_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

父类基本活动

open class BaseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.comm_toolbar)
val toolBar =
layoutInflater.inflate(R.layout.comm_toolbar,
null,false) as androidx.appcompat.widget.Toolbar
setSupportActionBar(toolBar)
}
}

主活动

class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<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" />
</androidx.constraintlayout.widget.ConstraintLayout>

这是因为您的 MainActivity 的 setContentView 将activity_main布局设置为内容视图。该布局中没有工具栏。不再设置基本活动的内容视图,因此设置支持操作栏(工具栏(不再工作。

您可以通过在子活动中添加工具栏或在约束布局中工具栏下方的基本活动的 xml 中使用视图存根并在父活动的 viewtub 中膨胀子活动的布局来处理此问题。这将保留工具栏并加载子活动的视图

最新更新