如何在android上动态更改按钮和文本颜色

ssk*_*ssk 7 android button

如何动态/编程地更改按钮文本颜色和按钮形状(矩形)?

Hir*_*ral 12

如果main.xml中有一个id = button1的按钮,那么可以按如下方式使用它:

setContentView(R.layout.main);

Button mButton=(Button)findViewById(R.id.button1);
mButton.setTextColor(Color.parseColor("#FF0000")); // custom color
//mButton.setTextColor(Color.RED); // use default color
mButton.setBackgroundResource(R.drawable.button_shape);
Run Code Online (Sandbox Code Playgroud)

R.drawable.button_shape(button_shape.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#70ffffff"
      android:centerColor="#70ffffff"
      android:endColor="#70ffffff"
      android:angle="270" />
  <corners 
        android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp"/>  
</shape>
Run Code Online (Sandbox Code Playgroud)

您可以拥有自己的形状文件.根据需要更改它.