Change ImageView source for some time after button click

天涯浪子 提交于 2019-12-20 07:27:26

问题


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);
    }
}
};


来源:https://stackoverflow.com/questions/21901355/change-imageview-source-for-some-time-after-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!