Android5.0之Toolbar使用教程



Toolbar是Android 5.0中新引入的一个控件,其出现的目的就是为了取代ActionBar,对于actionbar本人表示没有使用过。actionbar其实是系统UI,没有给开发者太多的权限来修改它,而toolbar则是应用UI,开发者可以随意改动它。

使用教程:

1、在Studio中直接在module的build.gradle文件中添加compile

dependencies {
    compile 'com.android.support:appcompat-v7:22.2.1'
}

2 修改当前activity的主题为Theme.AppCompat.NoActionBart,



3、而在Activity中我们就不要再继承ActionBarActivity了,AppCompatActivity

4、在layout布局中添加Toolbar

<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" tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

5、在Activity中调用setSupportActionBar方法将Toolbar的实例对象传入即可:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(toolbar);

运行效果如下,黑乎乎的,不过还是出来了,那么怎么改成我们之前的效果图呢。


6、通过修改style来实现,在values文件夹下的style中添加如下style,这个主题继承了Theme.AppCompat.NoActionBart主题,我们在maimfest中activity换成我们现在这个 android:theme="@style/AppTheme.Base"。

下面的colorPrimary用来定义应用的主色调,而colorPrimaryDark则是主色调偏暗的一个色调,最后的android:windowBackground则是定义整个Window窗口的背景色,

<style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="colorPrimary">@color/red0</item>
        <item name="colorPrimaryDark">@color/red1</item>
        <item name="android:windowBackground">@color/red2</item>
    </style>

7、在toolbar属性中加上android:background="?attr/colorPrimary"


效果图:



这里要注意的是底部导航栏的背景色只能在5.0以后的版本中才能修改,所以我们在这里将其单独放进v21的资源文件中,然后在mainfest中修改主题为android:theme="@style/AppTheme"

<style name="AppTheme" parent="AppTheme.Base">
        <item name="android:navigationBarColor">@color/red1</item>
    </style>


说明:这个效果只适合在Android 5.0版本的手机上,这个是我在模拟器上的运行效果,大家在Android studio中建立模拟器的时候可能会出现问题,大家可以参看我的另一篇关于创建模拟器的博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值