I am new to Android and Java but have managed to teach myself and find most answers to questions on stackoverflow without needing to ask questions. Until now....
Here goes, I have many colored buttons which, when clicked, change color to a range of different colors.
There are many buttons defined for example as:
<Button
android:id="@+id/button17"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@drawable/orange_button"
android:gravity="center"
android:onClick="onClick" />
Could someone please advise me how to change the android:background using code to change the above example to yellow, for example, when the button is clicked.
In the code below clickedButton is the ID of the button for which I need to change the background.
public void onClick(View v) {
int id=v.getId();
String clickedButton = getResources().getResourceEntryName(id);
Change button to Yellow here??
// Temporary code below to check which button was pressed
// and convert its number to an integer to eventually access an array
final TextView tvGameTimer = (TextView) findViewById(R.id.tvGameTimer);
int buttonNumber = Integer.parseInt(clickedButton.substring(6,8));
tvGameTimer.setText("" + buttonNumber);
}
I am using custom button styles to define the button colors:
res/drawable/yellow_button.xml
res/drawable/blue_button.xml
res/drawable/red_button.xml
res/drawable/orange_button.xml
res/drawable/green_button.xml
For now I just need to work out how to change the button from Orange to Yellow. I can then add the logic to change the colors as and when the app requires.
Many thanks for any help.
setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.
Create a new XML file in the res/drawable/ directory (name it something like button_custom.xml ). Insert the following XML: <?xml version="1.0" encoding="utf-8"?> This defines a single drawable resource, which will change its image based on the current state of the button.
A StateListDrawable is a Drawable object that uses a different image to represent the same object, depending on what state the object is in. For example, a Button can exist in one of several states (pressed, focused on, hovered over, or none of these).
I am supposing that the onClick method you post is of the same Button whose background you are trying to change. Use this code.
v.setBackgroundResource(R.drawable.yellow_button);
If onClick is not the method of the same button then, use
findViewById(R.id.button17).setBackgroundResource(R.drawable.yellow_button);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With