Reputation: 190
I haven't been able to find quite what I am trying to do on SO, but I feel like it should be such a common interface need that there must be a straightforward way of accomplishing this that I'm missing.
In my style.xml I have two button styles, a standard "active" button and an "inactive" button.
<style name="ButtonStandard">
<item name="android:background">@color/colorGreen</item>
<item name="android:textColor">@android:color/white</item>
<item name="android:padding">@dimen/element_padding</item>
</style>
<style name="ButtonInactive">
<item name="android:background">@color/colorLight</item>
<item name="android:textColor">@android:color/black</item>
<item name="android:padding">@dimen/element_padding</item>
</style>
I am setting one button to ButtonStandard
and the other to ButtonInactive
. When I click the inactive button, I want to change it to use the ButtonStandard
type and vice versa. I don't want to programmatically set the styles individually in case I decide to later change the button styles and it would be unreliable to have to change it in every location.
activeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
activeButton.[somehowsetstyle](R.style.ButtonInactive);
inactiveButton.[somehowsetstyle](R.style.ButtonStandard);
}
});
How can I change between these styles when users click on buttons? The most important is to not have to set specific styles within the code which is just a last resort imho.
Thanks!
Solution Notes
Generally I followed the solution below but instead I created the selector as a drawable and used android:drawable
instead because it seems the button background needs that, even if just specifying a color. I also used state_activated
rather than enabled so that it is only changing the look of the button and doesn't prevent clicks.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="false"
android:drawable="@color/colorPrimaryDark" />
<item android:state_activated="true"
android:drawable="@color/colorGreen" />
<item android:drawable="@color/colorGreen" />
In XML
android:background="@drawable/selector_btn_bkg"
android:state_activated="false"
In Java
myButton.setActivated(true);
Upvotes: 1
Views: 4012
Reputation: 2606
What you are looking for is ColorStateList
drawable/my_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="@color/enabled_color"/>
<item android:color="@color/enabled_color"
android:state_enabled = "true"/>
<item android:color="@color/disbaled_color"
android:state_enabled = "false"/>
</selector>
my_view.xml
...
<Button
android:id="@+id/my_button"
android:enabled="false"
android:background="@drawable/my_selector"/>
Java code
onClick(View v){
myButton.setEnabled(true);
}
Upvotes: 1