Toolbar比Actionbar的功能更加强大,但第一行代码上对toolbar的讲解已经不再适用Android Studio 3.5版本。最开始的import android.support.v7.widget.Toolbar已经不再适用,转而成为import androidx.appcompat.widget.Toolbar;
下面是Toolbar完整的创建代码:
1.首先是修改values下的style
<resources>
<!-- Base application theme. --><![CDATA[
]]><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">//此处修改为NoActionBar,也可以自定义一个style
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
2.在AndroidMainfest添加一行代码
<activity android:name=".MainActivity"
android:theme="@style/AppTheme">//此行代码必须添加!!
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
3.在布局中加入Toolbar
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/colorPrimary"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
4.在MainActivity中导包
import androidx.appcompat.widget.Toolbar;
5.设置这个布局
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}