android:动态设置按钮样式



我的布局中有两个按钮。此外,我定义了不同的样式,我想为按钮1动态设置样式1或样式2,为按钮2动态设置样式2。这两个按钮都在我的xml文件中定义。我发现没有办法在安卓系统中动态更改样式。我想知道是否有办法绕过这个问题

是的,您可以这样做。

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条件,不要忘记像我在上面的代码中所做的那样定义您的按钮。

最新更新