How to change the image of the button with each press?

I created a button in layout . In the Drawable folder, I created an XML file called btn01_state . btn01_state.xml assigned to button i created using android: background=@drawable /btn01_state "

Now button has the default value image img1.when I click on button , image1 changes to img2, and as soon as I release the mouse button, image2 will again change to img1.

what i want to do is to change the button image with evey click.

for example, initially btn01 has img01

if btn01 is pressed ==> install img from btn01 to img02 and save img02 until btn01 is pressed again. Now btn01 has img02.

When btn01 is pressed, set img01 to btn01.

I hope this further clarifies what I want to do.

btn_selector

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/android_blue" android:state_pressed="true" /> <item android:drawable="@drawable/ic_launcher" android:state_focused="true" /> <item android:drawable="@drawable/ic_launcher" /> 

main.xml

 <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/btn01" android:background="@drawable/btn01_state"/> 
+6
source share
3 answers

You can easily do this in code.

 boolean isPressed = false; button.setOnClickListener(buttonListener); OnClickListener buttonListener = new OnClickListener() { @Override public void onClick(View v) { if(isPressed) button.setBackgroundResource(R.drawable.icon1); else button.setBackgroundResource(R.drawable.icon2); isPressed = !isPressed; } }; 
+17
source

Easy way

 btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.locationbutton_on)); } }); 
+1
source

Do it in code, perhaps. Place the listener on the button, and when the button is pressed, the background will be changed.

0
source

Source: https://habr.com/ru/post/915016/


All Articles