随着新版本安卓sdk的发布,原有的Actionbar已经被弃用,被Toolbar所代替。下面我来给大家介绍下如何使用Toolbar来代替Actionbar
布局文件和样式
首先定义一个toolbar.xml文件,内容如下所示
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark" />
- android:background 为背景设置
- app:theme 为样式设置
随后在项目的styles.xml中添加如下内容,并保证AndroidManifest.xml的application标签下有对该样式的引用
...
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
...
- AndroidManifest.xml的样式引用参考代码如下
<application
android:name=".Application"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
确保页面布局中存在对toolbar.xml的引用,参考代码如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ll_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<Button
android:id="@+id/btn_submit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/view_margin_x"
android:layout_marginRight="@dimen/view_margin_x"
android:layout_marginTop="@dimen/view_margin_x"
android:onClick="submit"
android:text="你好" />
</LinearLayout>
代码部分
首先保证Activity页面继承自android.support.v7.app.AppCompatActivity
在页面中的代码部分如下所示
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Toolbar toolbar = (Toolbar)this.findViewById(id.toolbar);
setSupportActionBar(toolbar);
//设置标题
toolbar.setTitle("标题");
}
- 当setSupportActionBar()方法调用完成后,可以通过getSupportActionBar()得到设置完成后的Actionbar对象,以此来调用Actionbar的原有方法,如显示回退按钮等