Andriod5.0 Button样式

Android5.0引入了Material Design,许多原生控件都带有了MD的特效,近期正好刚刚接触Material Design,于是想着把做过的项目的UI进行一下更新。
在layout文件中按往常一样定义如下button:
   <Button
       android:id="@+id/btn_login"
       android:layout_width="match_parent"
       android:layout_height="50dp"
       android:layout_centerInParent="true"
       android:text="@string/login"
       android:textColor="@color/white"
       android:textSize="20sp"/> 
得到的即是带有raise和ripple(水波纹)效果的button。然而这个button的背景颜色是灰色的,与项目主题不搭,自然的我想到改变一下button的背景色,同时还想改一下圆角弧度,于是在上述的代码中加上了一句:
android:background="@drawable/button_login"
运行程序,发现button的形状和背景颜色确实改变了,但是MD效果却都没有了。
这是为什么呢。
经查询stackoverflow,得知是自定义的background覆盖了button默认的样式,而MD效果都是写在button的默认样式中。
button的默认样式如下:
<style name="Widget.Material.Button">
        <item name="background">@drawable/btn_default_material</item>
        <item name="textAppearance">?attr/textAppearanceButton</item>
        <item name="minHeight">48dip</item>
        <item name="minWidth">88dip</item>
        <item name="stateListAnimator">@anim/button_state_list_anim_material</item>
        <item name="focusable">true</item>
        <item name="clickable">true</item>
        <item name="gravity">center_vertical|center_horizontal</item>
    </style>
这里我不太理解的是,动画效果写在stateListAnimator中,而自定义的背景应该只是覆盖了background,为什么运行时连动画效果也没有了。
那如果我既想要MD的动画效果,又想按照自己的意思设计button的样式,应该怎么做呢。
stackoverflow和CSDN博客中给出的方法,我们可以在style.xml文件中自定义一个style,这个style继承button的默认style,同时在该style中修改我们想要进行定制的属性,比如button的背景颜色,如下所示:
<style name="LoginButton" parent="@android:style/Widget.Material.Button">
        <item name="android:colorBackground">@color/colorPrimary</item>
</style>
定义好style以后,在layout中的button标签下,加入:
android:theme="@style/LoginButton"
即可。
接下来再次运行程序,发现MD效果虽有,背景颜色却并没有改变。
我用的机型是中兴天机,系统版本是Android5.0.2,为什么继承了默认的button样式并修改了背景颜色属性但是却没有对应的效果,我现在还没想明白,希望各位不吝赐教。
最后只好再试试另外一个方法,即在button标签中加入
android:backgroundTint="@color/colorPrimary"
运行程序,button的背景颜色改变了,MD效果也还在。只是没有自定义的圆角弧度和stroke了。

猜你喜欢

转载自blog.csdn.net/VanEasley/article/details/62442314
今日推荐