Skip to content

Toolbar

Toolbar相比于自带的标题栏,能有更多的扩展性,更为灵活。

现在res/themes/themes.xml中,把自带的标题栏关闭掉:

xml
<style name="Theme.MaterialDemo" parent="Theme.MaterialComponents.Light.NoActionBar">

然后在activity_main.xml里面设置布局:

xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.activity.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap">
        </androidx.appcompat.widget.Toolbar>

        <include layout="@layout/drawer_layout"/>
    </LinearLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

其中coordinatorlayout相当于一个加强版的FrameLayout,<include layout="@layout/drawer_layout"/>是在下面引入我们的一个drawerLayout的布局,使用<include layout=""/>可以直接引入布局并且可以直接绑定控件

然后在MainActivity.kt中:

kotlin
val toolbar: Toolbar = findViewById(R.id.toolbar)
toolbar.title = "玩Android" //设置吧toolbar的标题
toolbar.setTitleTextColor(Color.WHITE) //设置标题字体颜色
setSupportActionBar(toolbar) //加载toolbar

就完成了对toolbar的设置。

DrawerLayout+NavigationView

DrawerLayout本身就是一种抽屉式布局,我们通常会搭配着NavigationBottom使用,然后抽屉栏里面的布局可以用NavigationView这个自带的布局,可以很容易实现头像加列表的形式,效果如下:

drawer_layout.xml布局如下:

xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 这里是DrawerLayout外面的布局,即主页面 -->
   
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <include layout="@layout/homepage"/>
    </LinearLayout>
    
    <!-- 下面的就是DrawerLayout里面的布局 -->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="false"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>


</androidx.drawerlayout.widget.DrawerLayout>

上面代码中android:layout_gravity="start"这一行是必须指定的,且要与DrawerLayout的打开方式一样

其中列表使用的是menu资源,activity_main_drawer.xml内容如下:

xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_about"
            android:icon="@drawable/ic_about"
            android:title="关于" />
    </group>
</menu>

MainActivity.kt里面的设置:

kotlin
    private fun setNavigationColumn() {
        val drawerLayout: DrawerLayout = findViewById(R.id.drawerLayout)
        
        //对toolbar的设置
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        toolbar.title = "玩Android"
        toolbar.setTitleTextColor(Color.WHITE)
        setSupportActionBar(toolbar)
        
        //加载打开抽屉栏的按钮
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true) //按钮可以让用户返回到上一级的活动或片段
            it.setHomeAsUpIndicator(R.drawable.ic_menu) //将返回按钮设置成菜单图标
        }
        
        //关闭抽屉栏
        fun closeDrawer() {
            drawerLayout.closeDrawer(findViewById(R.id.nav_view))
        }

        //对抽屉栏里面的列表进行点击监听
        findViewById<NavigationView>(R.id.nav_view).setNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {

                R.id.nav_about -> {
                    val intent = Intent(this, AboutActivity::class.java)
                    startActivity(intent)
                }

            }
            closeDrawer()
            true
        }
        
        //添加对DrawerLayout的监听,使得在打开与关闭时toolbar能切换不同的图标
        toggle = object :
            ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name) {
            override fun onDrawerClosed(drawerView: View) {
                super.onDrawerClosed(drawerView)
            }

            override fun onDrawerOpened(drawerView: View) {
                super.onDrawerOpened(drawerView)
            }
        }
        toggle.syncState() //同步toolbar和DrawerLayout的状态
        drawerLayout.addDrawerListener(toggle)
    }

BottomNavigationView+ViewPager2

而homepage页面我们则采用BottomNavigationView+ViewPager2的形式。

homepage.xml:

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">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/homepage_navigation_bottom"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:itemTextColor="@color/nav_bottom_text_select"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/menu_bottom" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/bottom_navigation_viewpage2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toTopOf="@+id/homepage_navigation_bottom"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

上面的@menu/menu_bottom也是菜单资源文件,加载了底部导航按钮:

xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/bottom_home"
        android:icon="@drawable/bottom_home"
        android:title="首页"/>

    <item
        android:id="@+id/bottom_public"
        android:icon="@drawable/bottom_public"
        android:title="公众号" />

    <item
        android:id="@+id/bottom_navigation"
        android:icon="@drawable/bottom_navigation"
        android:title="导航"/>
</menu>

ViewPager2的Adapter:

kotlin
package com.generlas.winterexam.view.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

class ViewPager2Adapter(fragment: FragmentActivity, private val list: MutableList<Fragment>) :
    FragmentStateAdapter(fragment) {
    override fun getItemCount(): Int {
        return list.size
    }

    override fun createFragment(position: Int): Fragment {
        return list[position]
    }

}

因为切换的是fragment,所以直接继承FragmentStateAdapter

MainActivity.kt

kotlin
//设置底部导航按钮
    private fun setBottomNavigation() {
        //绑定视图
        val mNavBottom: BottomNavigationView = findViewById(R.id.homepage_navigation_bottom)
        val mBottomViewpager2: ViewPager2 = findViewById(R.id.bottom_navigation_viewpage2)

        mNavBottom.itemIconTintList = null //取消导航栏的默认颜色
        //将fragment添加进适配器
        val fragmentList: MutableList<Fragment> = ArrayList()
        fragmentList.add(HomeFragment())
        fragmentList.add(PublicFragment())
        fragmentList.add(NavigationFragment())
        mBottomViewpager2.adapter = ViewPager2Adapter(this, fragmentList)

        mBottomViewpager2.isUserInputEnabled = false //禁用ViewPager2的手势滑动

        //fragment切换时底部导航跟着切换
        mBottomViewpager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mNavBottom.menu.getItem(position).isChecked = true
            }
        })

        //底部导航切换时fragment跟着切换
        mNavBottom.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.bottom_home -> {
                    mBottomViewpager2.currentItem = 0
                    return@setOnItemSelectedListener true
                }

                R.id.bottom_public -> {
                    mBottomViewpager2.currentItem = 1
                    return@setOnItemSelectedListener true
                }

                R.id.bottom_navigation -> {
                    mBottomViewpager2.currentItem = 2
                    return@setOnItemSelectedListener true
                }
            }
            false
        }
    }

自定义toolbar的菜单图标

如上图所示,toolbar能自定义添加按钮(如搜索按钮)

只需要在MainActivity.kt中添加:

kotlin
    // 处理toolbar上抽屉开关等图标的点击事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        //设置抽屉栏按钮的点击
        if (toggle.onOptionsItemSelected(item)) {
            return true
        }

        return when (item.itemId) {
            R.id.search -> {
                val intent = Intent(this, SearchActivity::class.java)
                startActivity(intent)
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

    //加载toolbar的搜索按钮
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_toolbar_main, menu)
        return true
    }

同样也需要添加目录资源menu_toolbar_main.xml:

xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:icon="@drawable/ic_search"
        android:title="search"
        app:showAsAction="always"/>
</menu>

通过上述方法,你就可以很容易搭建起一个基本的页面框架了。