ToolBar入门

随着新版本安卓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的原有方法,如显示回退按钮等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值