[英]How do I programmatically change the style of a Material Component Text Button in Android?
我有一個材質文本按鈕<Button android:id="@+id/button" style="@style/Widget.MaterialComponents.Button.TextButton"/>
我想在運行時更改顏色。 所以我使用button.setTextColor(Color.rgb(10, 10, 10))
設置文本顏色。 不幸的是,這不會改變可繪制的背景,所以當我點擊按鈕時,它的波紋顏色沒有改變。 我猜我需要用諸如attackButton.background = getDrawable(R.drawable.ripple)
類的東西來改變背景,但我不知道如何填充ripple.xml
。 這種方法對更改按鈕文本顏色和波紋有意義嗎? 如果是這樣,我應該如何編寫ripple.xml
?
要更改MaterialButton
的顏色,您可以使用:
button.setBackgroundTintList
更改背景色調。 您應該使用選擇器。button.setRippleColor
改變波紋顏色。 同樣在這種情況下,您應該使用選擇器(見下文)button.setTextColor
改變文本的顏色。 同樣在這種情況下,您應該使用選擇器。它是波紋顏色中使用的默認選擇器:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:alpha="@dimen/mtrl_low_ripple_pressed_alpha" android:color="?attr/colorPrimary" android:state_pressed="true"/>
<item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true" android:state_hovered="true"/>
<item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true"/>
<item android:alpha="@dimen/mtrl_low_ripple_hovered_alpha" android:color="?attr/colorPrimary" android:state_hovered="true"/>
<item android:alpha="@dimen/mtrl_low_ripple_default_alpha" android:color="?attr/colorPrimary"/>
</selector>
你試過RippleDrawable嗎? 然后只需 Button.setBackground() 到不同的資源甚至選擇器xml。 如果帶有選擇器的波紋對您來說還不夠,可以設置波紋蒙版本身
我的瑞波文件
<ripple android:color="#ffff0000">
<item android:id="@android:id/myRippleMask"
android:drawable="@android:color/white" />
</ripple>
以編程方式:
LayerDrawable myRipple = ContextCompat.getDrawable(context, drawable.myRipple.xml);
myRipple.setDrawableByLayerId(R.id.myRippleMask,Color.rgb(10, 10, 10));
每個面具都是不同的顏色
textcolor、backgroundcolor和ripplecolor的一行代碼編程無資源文件方法:
MaterialButton myMaterialButton = new MaterialButton(this);
myMaterialButton.setTextColor(Color.RED);
myMaterialButton.setBackgroundColor(Color.GRAY);
myMaterialButton.setRippleColor(ColorStateList.valueOf(Color.RED));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.