【发布时间】:2020-07-17 02:52:42
【问题描述】:
我的布局中有两个按钮。我也定义了不同的样式,我想为按钮 1 动态设置样式 1 或样式 2,为按钮 2 设置样式 2。这两个按钮都在我的 xml 文件中定义。 我看到没有办法在 Android 中动态更改样式。我想知道是否有办法解决这个问题
【问题讨论】:
我的布局中有两个按钮。我也定义了不同的样式,我想为按钮 1 动态设置样式 1 或样式 2,为按钮 2 设置样式 2。这两个按钮都在我的 xml 文件中定义。 我看到没有办法在 Android 中动态更改样式。我想知道是否有办法解决这个问题
【问题讨论】:
是的,你可以这样做。
private Button testButton1, testButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
testButton1 = findViewById(R.id.btn_resource_name1)
testButton2 = findViewById(R.id.btn_resource_name2)
//This is how you set the style:
testButton1.setBackgroundResource(R.drawable.style1);
testButton2.setBackgroundResource(R.drawable.style2);
//Assuming your styles.xml are in drawable directory
}
就是这样!只需根据您的程序添加任何 if-else 条件,不要忘记像我在上面的代码中所做的那样定义您的按钮。
【讨论】:
android:text="your text" 的文本,并且颜色很重要。当我尝试代码时,我的按钮是黄色的,但文本颜色也是白色的,所以我无法清楚地看到文本。确保将 android:textColor 设置为可见颜色。