安卓Toolbar使用 Demo(Kotlin)
內容介紹
本文介紹Toolbar的基本使用方法,包含如下幾項:
- 設定標題內容
- 設定左側圖示
- 增加選單項
- 對選單項設定點選事件
實現效果圖


使用方法
- styles.xml檔案
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>
- activity_main.xml檔案中增加toolbar
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navigationIcon="@mipmap/back" app:title="標題" />
- Activity中使用(下面的toast函式來自另外一個類,請下載原始碼檢視)
toolbar.inflateMenu(R.menu.edit_menu) toolbar.setNavigationOnClickListener { toast("Back") } toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_search -> toast("Search") R.id.action_del -> toast("Delete") R.id.action_warn -> toast("Warn") R.id.action_settings -> toast("Settings") } false }
原始碼
https://gitee.com/cxyzy1/toolbarDemo
附錄
參考資料:
https://blog.csdn.net/flykozhang/article/details/50280109
https://blog.csdn.net/da_caoyuan/article/details/79557704安卓開發技術分享: https://www.jianshu.com/p/442339952f26
更多技術總結好文,請掃碼關注:「程式園中猿」
