当用户从微调器中选择项目时,如何以编程方式更改按钮颜色



我正在开发一个Android应用程序,在这个应用程序中我使用了一个自定义微调器和一个按钮。我希望当用户从微调器中选择一个项目时,我的按钮颜色应该改变。

您可以通过将onItemSelected侦听器设置为所需的项数量或项集,然后在该实现中更改颜色来实现这一点,这样就可以实现:


Button myButton;
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos);
If(pos == 1){
Mybutton.setBackgroundColor(R.color.red);
//where R.color.red is a color resource reference under the android resource (res) folder, you can add more colours to colors.xml to have more colour values
// you can also set the button to change colours for each new position (pos), where position represents the order of items in your spinner, note that the first position starts at 0 so in that code pos == 1 is actually talking about to second item on the spinner adapter 
}

您还可以使用onNothingSelected方法来实现默认按钮颜色,该颜色仅在用户选择任何微调器项目之前处于活动状态,因此将是:

public void onNothingSelected(AdapterView<?> parent) {
myButton.setBackgroundColor(R.color.white);
}

如果你使用kotlin,你可以通过安卓工作室的代码转换功能将代码转换为kotlin代码。

这样,按钮的颜色就会相应地改变。

因为你没有任何代码,所以我会想出一个主意:

第一:您将创建一个类作为(java(:

public class GlobalConstant {
public static int click1;
public static int click2;
}

当您selects an item from spinner之后,您将在代码中设置click1的值为:

GlobalConstant.click1=1

和:

if (GlobalConstant.click1==1){
Button.setBackgroundColor(Color.BLACK);
}

此处Button =findViewById<Button>(R.id.startButton)(kotlin(

最新更新