Issue
I'm working on an Android Application and in this application I used a custom spinner and a button. I want when user selects an item from spinner my button color should change.
Solution
You can achieve that by setting an onItemSelected listener to the amount or set of items you want and then changing the color in that implementation, so that would be something like this:
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
}
You can also have onNothingSelected method to implement a default button color which will only be active right before the user selects any spinner item, so that will be:
public void onNothingSelected(AdapterView<?> parent) {
myButton.setBackgroundColor(R.color.white);
}
If you use kotlin, you can just convert the code to kotlin code with Android studio code conversion feature.
That way, the button color changes accordingly.
Answered By - DeveloperForce
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.