Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Button color changing on onClick?

Tags:

android

button

I am facing a problem .

I have two Button object.

ButtonA ButtonB

Requirement:-

When ever I press ButtonA the color of button should be changed and it should remain same until I clicked on ButtonB.

After click on ButtonB same thing should be working i.e for ButtonA

if (v == btn)
{
    btn.setBackground(mActivity.getResources().getDrawable(R.drawable.button_color_chnager));
}

XML:

<item android:state_focused="true" android:state_pressed="true" 
            android:drawable="@drawable/ic_launcher" /> 
like image 557
Monty Avatar asked Jun 19 '13 11:06

Monty


People also ask

How do you change the button color after clicking?

To change a button's color every time it's clicked:Add a click event listener to the button. Each time the button is clicked, set its style. backgroundColor property to a new value. Use an index variable to track the current and next colors.

How do I change the button color on click flutter?

Go to your main. Inside the MaterialApp, find the ThemeData widget. Add the elevatedButtonTheme property inside and assign the ElevatedButtonThemeData(). Add the style property and change the color as you would change it for normal ElevatedButton. Place the ElevatedButton widget anywhere in your Flutter app and see.

How do you change the color of a click button in CSS?

To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste. In the . button selector, you use background-color:#0a0a23; to change the background color of the button.


1 Answers

buttoncolor.xml

<?xml version="1.0" encoding="utf-8"?> 
  <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
      <item android:state_focused="true" android:state_pressed="true" 
            android:drawable="@drawable/bgalt" /> 
      <item android:state_focused="false" android:state_pressed="true" 
            android:drawable="@drawable/bgalt" /> 
      <item android:drawable="@drawable/bgnorm" /> 
  </selector>

Now use like below:

b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
         b2.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));
    }
});

b2 = (Button) findViewById(R.id.b2);
b2.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
         b1.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));
    }
});
like image 137
Sagar Maiyad Avatar answered Sep 21 '22 11:09

Sagar Maiyad