Reputation: 257
I have a button:
<Button
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="@string/male"
android:id="@+id/btn_mgen_m"
android:layout_gravity="center_horizontal"
android:background="@drawable/bg_tgl_btn_left"
android:textColor="#444444" />
and I changed its color like this:
btnMgenM = (Button) findViewById(R.id.btn_mgen_m);
btnMgenM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnMgenM.setBackgroundColor(Color.parseColor("#dca8c3"));
}
});
The background color is changed properly but it seems to remove the background drawable. The round radius, text color and border are removed just the simple colored button is left. I want to change the background color when I click this button, but not change anything else.
How can I do this?
Upvotes: 6
Views: 911
Reputation: 1544
You can do like the following :
create in your res/drawable
button_style.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorGreyFirst" />
<corners android:radius="16dp" />
<stroke
android:width="3dp"
android:color="@color/colorBlackTransparent" />
</shape>
</item>
<item android:state_selected="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorGreyFirst" />
<corners android:radius="16dp" />
<stroke
android:width="3dp"
android:color="@color/colorBlackTransparent" />
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorGreyFirst" />
<corners android:radius="16dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorGrey" />
<corners android:radius="16dp" />
<stroke
android:width="3dp"
android:color="@color/colorGrey" />
</shape>
</item>
and in your xml :
<Button
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="@string/male"
android:id="@+id/btn_mgen_m"
android:layout_gravity="center_horizontal"
android:background="@drawable/button_style"
android:textColor="#444444" />
and in your color.xml
you could specify your colors.
Or you can simply do like that :
btnMgenM = (Button) findViewById(R.id.btn_mgen_m);
btnMgenM.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnMgenM.setBackgroundColor(getResources().getColor(R.color.yourColor));
}
});
And add this to your color.xml
<color name="yourColor"> #dca8c3</color>
Hope it helps.
Upvotes: 0
Reputation: 4959
Try this both of line
btnMgenM.setBackgroundResource(0);
btnMgenM.setBackgroundColor(Color.parseColor("#dca8c3"));
Upvotes: 1