簡體   English   中英

Android。 如何以編程方式更改按鈕的背景顏色

[英]Android. How to programatically change background color of button

我需要以編程方式創建 Button。 我的按鈕可以隨機着色。 但是,我需要設置按鈕的背景顏色以及按鈕位於 state PRESSED 時的背景顏色。

也就是說,按鈕在其正常 state 中的背景顏色應該與用戶按下按鈕時的背景顏色不同。

例如,當我需要不同的按鈕背景時,根據 state,我使用選擇器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/shape_not_pressed" android:state_pressed="false" />
    <item android:drawable="@drawable/shape_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/shape_not_pressed" />
</selector>

在我的 xml 按鈕中:

  android:background="@drawable/selector_button"

如果您提前了解所需的背景,這是一個可行的解決方案。 但是,就我而言,我正在動態獲取按鈕的背景(pressed_bg 和 not_pressed_bg),因此這種方法對我不起作用。 是否可以以編程方式實現這一點?

PS我需要壓制效果

請幫我。

您可以像這樣以編程方式檢查和設置 colors。

if(someButton.isPressed){
     val pressedRandomColor = getPressedRandomColor()
     someButton.setBackgroundColor(pressedRandomColor)
 }else {
     val randomColor = getRandomColor()
     someButton.setBackgroundColor(randomColor)
 }

getPressedRandomColor() 和 getRandomColor() 的邏輯你需要自己定義,它應該返回 Int 值。

您可以創建一個顏色代碼列表並在單擊按鈕時隨機傳遞顏色代碼以設置按鈕背景顏色。

yourButton.setBackgroundColor(Color.parseColor("#0060AB"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM