Sultan Fikri Sultan Fikri - 2 months ago 24
Android Question

Change image of button when pressed, make image of button not change when released

When I press the button image changes, but my problem is when I release the button, the image changes again (does not retain images). I am new to Java programming.

My layout :

<Button
android:background="@drawable/volume"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>


And this is my XML in drawable:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/volume_off" /> <!-- pressed -->

<item android:drawable="@drawable/volume_on" /> <!-- default -->



Answer

If you want to change the image of your button permanently when you click it, it convenient to do it programmatically, inside the onClick void of your button. For example if

image1: R.drawable.image_first image2: R.drawable.image_second

and in your XML layout file you have:

 <Button
    android:background="@drawable/volume"
    android:layout_width="90dp"
    android:layout_height="90dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:onClick="click"/>

in the Activity you can do:

public Class myActivity extends Activity{

Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myactivity_layout);
    mButton = (Button) findViewById(R.id.button);
}

public void click(View v){
   mButton.setBackgroundResource(R.drawable.image_second);
}

}

If you want to come back to the previous image after clicking again, just save the state of your button (boolean clicked = true/false) and put an if statement inside the public void click.

Comments