Reputation: 47
I want to change the button's colour when I clicked. But when I clicked the another second button, the first button must be coloured the with the last colour.
I mean that, when I clicked whic button, it must be coloured with blue and the other buttons must be non-colour. here is the code;
if(view == button1)
{
button1.setBackgroundColor(Color.BLUE);
}
else if(view == button2){
button2.setBackgroundColor(Color.BLUE);
}
else if(view == button3){
button3.setBackgroundColor(Color.BLUE);
}
else if(view == button4){
button4.setBackgroundColor(Color.BLUE);
}
Upvotes: 0
Views: 9995
Reputation: 6553
change this line:
button2.setBackgroundColor(Color.BLUE);
and try this:
button2.setBackgroundColor(Color.parseColor("#5AC8E2"));
Upvotes: 0
Reputation: 10623
When you need to change the background color of the button when it is pressed, then u have to follow these ,
//create an xml file, like layout_a.xml file in drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_pressed" /> <!--btn pressed -->
<item android:drawable="@drawable/btn_normal" /> <!-- Normal condition -->
</selector>
//Now this file should be in a drawable folder and use this single line code in button code to get all the properties of this xml file .
<Button
android:id="@+id/street_btn"
android:layout_width="wrap_content"
android:background="@drawable/layout_a" > <!-- your required code -->
</Button>
Upvotes: 0
Reputation: 24181
//init all buttons background : GRAY
public void initButtons(){
button1.setBackGroundColor(Color.GRAY);
button2.setBackGroundColor(Color.GRAY);
button3.setBackGroundColor(Color.GRAY);
button4.setBackGroundColor(Color.GRAY);
}
and in the implementation of the OnClick : do this :
@Override
public void onClick(View v ) {
initButtons();
((Button)v).setBackGroundColor(Color.BLUE);
}
Hope it helps :)
Upvotes: 3
Reputation: 3790
you can use drawable selector to define the button states in xml then by default the clicked button will be changed to the color you want only when it is in click state.
Create a new xml file in your drawable folder for example blue_btn.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/yourColor"
android:state_pressed="true" android:state_enabled="true" />
<item android:drawable="@color/yourOtherColor" android:state_enabled="true" />
</selector>
then use R.drawable.blue_btn as a background for your buttons
refer to: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
Upvotes: 2
Reputation: 10948
Keep a reference to the previously modified Button. When you have a new click, set that previously referenced Button back to un-colored, set the current button to Blue then set that reference to the current button.
Upvotes: 0