国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Android Button按鈕點擊背景和文字變化操作

瀏覽:81日期:2022-09-22 18:31:09

Android 原生的按鈕點擊狀態是有變化的,但是如果是自己加了一個.png格式的圖片為背景色,按鈕點擊就不會有任何效果,為了達到點擊按鈕有一閃的效果,我們就需要準備兩張圖進行切換, 而且文字也要變色,老規矩廢話不多說直接上代碼:

按鈕背景圖片放在 drawable/background_button.xml

<?xml version='1.0' encoding='utf-8'?><selector xmlns:android='http://schemas.android.com/apk/res/android'> <item android:drawable='@drawable/bg_press' android:state_pressed='true'/> <item android:drawable='@drawable/bg_normal' android:state_enabled='true'/> <item android:drawable='@drawable/bg_normal'/></selector>

準備兩張圖片一張為bg_press.png, 一張為 bg_normal.png。

在需要變化的按鈕中設置:

<Button android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_alignParentRight='true' android:layout_centerVertical='true' android:layout_marginRight='50dp' android:focusable='false' android:gravity='center' android:textSize='24px' android:text='@string/str_tethering_modify' android:background='@drawable/background_button' />

這有背景色變化就解決完了,下面到按鈕上的文字了,現在點擊按鈕按鈕上的文字是沒有變化的,為了達到按鈕文字顏色的變化我們再新建一個xml文件。

按鈕顏色變化 drawable/button_color.xml

<?xml version='1.0' encoding='utf-8'?><selector xmlns:android='http://schemas.android.com/apk/res/android'> <item android:state_pressed='true' android:color='#975508'/> <item android:state_focused='false' android:state_pressed='false' android:color='#E5960E'/> <item android:state_focused='true' android:color='#975508'/> <item android:state_focused='false' android:color='#E5960E'/></selector>

加入到我們的按鈕textColor中

<Button android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_alignParentRight='true' android:layout_centerVertical='true' android:layout_marginRight='50dp' android:focusable='false' android:gravity='center' android:textSize='24px' android:textColor='@drawable/button_color' android:text='@string/str_tethering_modify' android:background='@drawable/background_button' />

這樣直接使用背景和文字就都有點擊效果啦,但是如果有這樣一個需求,在某些條件下需要再設置按鈕文字的顏色button.setTextColor(color),這樣設置完后,發現我們按鈕上文字點擊又沒有變化了,我之前試著直接 button.setTextColor(R.drawable.button_color);發現這樣是沒有任何用處的。這樣就需要使用 ColorStateList 來解決,顧名思義,就是定義顏色的狀態列表,通過監聽按鈕不同狀態來設置不同的顏色,

老規矩,廢話不多說了,直接貼代碼:

/** * 按鈕點擊顏色變化 */ private ColorStateList colorStateList; colorStateList = (ColorStateList)getResources().getColorStateList(R.drawable.button_color); if(xxx){ button.setTextColor(Color.White); }else{ button.setTextColor(colorStateList); }

這樣就完美解決了按鈕點擊狀態的變化啦。

補充知識:android studio設置按鈕和背景融為一體也就是按鈕去除陰影

<Buttonandroid:layout_width='wrap_content'android:layout_height='wrap_content'android:text='@string/button_send'android:onClick='sendMessage' />

以上這篇Android Button按鈕點擊背景和文字變化操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Android
相關文章:
主站蜘蛛池模板: 桐城市| 潼南县| 鄂伦春自治旗| 峨边| 桂林市| 岑巩县| 修文县| 赤峰市| 文成县| 邢台市| 项城市| 祁门县| 阿坝县| 贵德县| 溆浦县| 赣州市| 昌图县| 年辖:市辖区| 临海市| 日土县| 吐鲁番市| 高密市| 九江县| 和平区| 靖安县| 饶河县| 绥阳县| 大竹县| 陆河县| 桃江县| 新营市| 聂荣县| 三门峡市| 康平县| 通山县| 江达县| 南涧| 治县。| 双流县| 冀州市| 聂拉木县|