Reputation:
I'm trying to change the style of a Button when someone clicks on it. I want to change both the background as the text colour. However, only the text color is changed. From that I conclude that the style is changed, but for some reason the background can't be overwritten.
I'm using this code in the onClick handler:
Button send_button = (Button) findViewById(R.id.button1);
send_button.setTextAppearance(context, R.style.activeButtonTheme);
The relevant styles in my styles.xml are:
<style name="buttonTheme">
<item name="android:background">@color/white</item>
<item name="android:textColor">@color/orange</item>
<item name="android:paddingTop">6dp</item>
<item name="android:paddingBottom">6dp</item>
<item name="android:layout_margin">2dp</item>
</style>
<style name="activeButtonTheme" parent="@style/buttonTheme">
<item name="android:background">@color/orange</item>
<item name="android:textColor">@color/white</item>
</style>
What's the problem here?
I do not want to set the background color from Java, I only want to change the style in Java.
Upvotes: 0
Views: 337
Reputation: 530
Use selector
for that purpose. Check this link for details(Custom background section) Regarding to your code, define appropriate selector.xml file in your resources directory, something like that:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_for_dissabled_button" android:state_enabled="false"/>
<item android:drawable="@drawable/drawable_for_pressed_button" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/drawable_for_enabled_button" android:state_enabled="true"/>
</selector>
Assign just created selector to the button in the layout file:
<Button android:id="@+id/your_button_id"
android:background="@drawable/selector" />
Upvotes: 1