在新的AppCompat库中,我们可以这样为按钮着色:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/follow"
android:id="@+id/button_follow"
android:backgroundTint="@color/blue_100"
/>
如何在我的代码中以编程方式设置按钮的色调?
我基本上是试图实现基于一些用户输入的按钮的条件着色。
根据文档,android的相关方法:backgroundTint是setBackgroundTintList(ColorStateList list)
更新
按照此链接了解如何创建颜色状态列表资源。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="#your_color_here" />
</selector>
然后使用
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
哪里contextInstance是一个Context的实例
使用AppCompart
btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
根据文档,android的相关方法:backgroundTint是setBackgroundTintList(ColorStateList list)
更新
按照此链接了解如何创建颜色状态列表资源。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="#your_color_here" />
</selector>
然后使用
setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
哪里contextInstance是一个Context的实例
使用AppCompart
btnTag.setSupportButtonTintList(ContextCompat.getColorStateList(Activity.this, R.color.colorPrimary));
这很容易在材质设计库的新材质按钮中处理,首先,添加依赖项:
implementation 'com.google.android.material:material:1.1.0-alpha07'
然后在你的XML中,使用这个按钮:
<com.google.android.material.button.MaterialButton
android:id="@+id/accept"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/i_accept"
android:textSize="18sp"
app:backgroundTint="@color/grayBackground_500" />
当你想改变颜色时,这是Kotlin中的代码,它没有被弃用,可以在Android 21之前使用:
accept.backgroundTintList = ColorStateList.valueOf(ResourcesCompat.getColor(resources,
R.color.colorPrimary, theme))