1:導入V7包
右鍵項目 ->open module setting ->Dependencies ->點擊+號-> 選擇Library Dependency-> 搜索“appcompat-v7”
打開app/build.gradle,發現已經成功引入
圖1.1
圖1.2
圖1.3
圖1.4
2:activity_main中修改文件
網上一般都采用了相對布局的方法,不知道原因,猜測是因為這樣的話就可以實現actionbar和toolbar共存並放在想放的位置上
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorPrimary" app:logo="@mipmap/app_logo" app:title="快速登錄注冊" app:titleTextColor="#fff" app:navigationIcon="@drawable/ic_menu" android:theme="@style/Base.Theme.AppCompat.Light" > </androidx.appcompat.widget.Toolbar> </RelativeLayout>
3:Mainactivity.java
在多次嘗試后,發現一件有趣的事情
Toolbar有兩個,如果引入錯誤的話就會無法使用,同時需要和之前在配置文件中的toolbar相同類型,不然就會出現一個android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar,大意就是找不到這個類(用3.2的寫法,會報如3.3所示的錯誤)
圖3.1
圖3.2
圖3.3