Change ImageView source for some time after button

2020-05-03 11:08发布

问题:

I have two buttons and one imageview:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"   
tools:context=".MainActivity"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" >

<ImageView
    android:id="@+id/dog"
    android:contentDescription="@string/desc"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/dogsec" />

<ImageButton
    android:id="@+id/barkk"
    android:contentDescription="@string/desc"
    android:background="@android:color/transparent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/dog"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="45dp"
    android:src="@drawable/bark" />

<ImageButton
    android:id="@+id/rrrr"
    android:background="@android:color/transparent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/barkk"
    android:layout_below="@+id/barkk"
    android:layout_marginRight="41dp"
    android:layout_marginTop="15dp"
    android:contentDescription="@string/desc"
    android:src="@drawable/rrr" />

</RelativeLayout>

a) I need to make Imageview change its' source to another one(I mean the image's default state is picture1, it should show picture2 and go back to picture1) on button "barkk" click. It should not show picture2 as long as barkk is pressed.

b) and I need to display picture3 as long as button rrrr is pressed.

I use exactly ImageView which should change its' source depending on case a) or b) as it is described above.

Help me please. Thanks in advance

回答1:

Use this code.

myButton.setOnClickListener(new OnClickListener() {
@Override
public boolean onTouch(View v, MotionEvent event) 
  {
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        myImageView.setImageResource(R.drawable.myNewImage);
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        myImageView.setImageResource(R.drawable.myNewImage);
    }
}
};