简体   繁体   中英

How to make an Imagebutton change Image onClick in and Back to its original on ClickOut in Java/Android Studio

So I have some Images of buttons that I created and I want to use them in android studio as ImageButtons.

在此处输入图片说明

Basically I want the ImageButton OnClick in to change its Image and OnClick out to return to its first Image.

I am trying this:

    View.OnClickListener imgButtonHandler = new View.OnClickListener() {

        public void onClick(View v) {
            goalsButton.setBackground(R.drawable.mygoalsclicked);

        }
    };

But I get the error:

In View cannot be applied to (Int)

Can that be done in Android Studio? And how? Does any one knows? Thank you.

Use ToggleButton
Instead ImageView

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

check.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use first Image -->
    <item android:drawable="@drawable/achievement"
          android:state_checked="true" />
    <!-- When not selected,  use second Image-->
    <item android:drawable="@drawable/achievementclicked"
        android:state_checked="false"/>

 </selector>

Are You Looking for?

<ImageView
    android:id="@+id/imageView11"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    app:srcCompat="@drawable/image_selector" />

image_selector.xml

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

In the onClick method you have to put this code:

ImageButton.setImageResource(R.drawable.your_image);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM