最後更新日期:2023 年 03 月 22 日

Dependencies

app/build.gradle

...

dependencies {
    ...
    implementation 'com.google.android.material:material:1.6.1'
}

變更 Theme

themes.xml

將 DarkActionBar 改為 NoActionBar

<resources xmlns:tools="http://schemas.android.com/tools">
    <style name="Theme.CatChat1004" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        ...
    </style>
</resources>

此時我們如果執行 app,就會發現原來的 appbar 消失了

activity_main.xml

加入 MaterialToolbar 到 layout 檔

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.MaterialToolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:id="@+id/toolbar"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>

此時如果執行,會發現出現了 Toolbar,但是卻沒有任何 app 的資訊。

MainActivity.kt

指定我們要使用的 Toolbar 有原本 App bar 的功能。

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

        val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
    }
}

此時我們如果執行 app,就會發現 appbar 再度出現。

Last modified: 2023 年 3 月 22 日

Author

Comments

Write a Reply or Comment

Your email address will not be published.