Android Button修改背景顏色及實現(xiàn)Button水波紋效果,效果如下:
?
以下基于API33(Android13.0),向下兼容至API24(Android7.0)。
1.修改Button背景
我們可以發(fā)現(xiàn)在布局xml文件中直接修改background是沒有作用的,會變成默認的主題色(themes.xml中的colorPrimary顏色,默認為紫色)
<Button
android:id="@+id/dialog_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:background="@drawable/ripple_grey_e"
android:text="確定"
android:textColor="@color/grey_3"
android:textSize="@dimen/main_text"
tools:ignore="TouchTargetSizeCheck" />
這是由于在Android4.1之后的開發(fā)中創(chuàng)建的Button是Material類型的,默認使用主題色的,所以我們需要替換主題色或者使用非Material類型的Button,修改如下:
<android.widget.Button
android:id="@+id/dialog_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:background="@drawable/ripple_grey_e"
android:text="確定"
android:textColor="@color/grey_3"
android:textSize="@dimen/main_text"
tools:ignore="TouchTargetSizeCheck" />
將Button修改為android.widget.Button標(biāo)簽即可。
2.實現(xiàn)按壓水波紋效果
首先在drawable文件夾中創(chuàng)建ripple類型的xml文件,例如我創(chuàng)建的ripple_grey_e.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/grey_e">
<item android:drawable="@color/selector_btn_transparent"/>
</ripple>
其中的@color/grey_e為colors.xml文件中定義的顏色(這個顏色就是水波紋的顏色,此處為淺灰色#eeeeee,示例動圖中為使效果明顯替換為了深灰色#333333),@color/selector_btn_transparent為color文件夾(推薦自建,也可以放在drawable文件夾中),selector_btn_transparent.xml內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--按壓下時-->
<item android:state_pressed="true" android:color="@color/grey_f7" />
<item android:color="@color/transparent"/>
</selector>
?grey_f7為淺灰色(#f7f7f7),transparent為透明色(#00ffffff)。
使用如下:文章來源:http://www.zghlxwxcb.cn/news/detail-466942.html
<android.widget.Button
android:id="@+id/dialog_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:background="@drawable/ripple_grey_e"
android:text="確定"
android:textColor="@color/grey_3"
android:textSize="@dimen/main_text"
tools:ignore="TouchTargetSizeCheck" />
?本示例采用顏色較淺,如果想使效果更加明顯,可以將顏色換為更加明顯的顏色。文章來源地址http://www.zghlxwxcb.cn/news/detail-466942.html
到了這里,關(guān)于Android Button修改背景顏色及實現(xiàn)Button水波紋效果的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!