问题
I would change imageView picture when it's pressed, and change it again when pressure is released. That ImageView contains picture of a button, and when is pressed i would give to user a feedback (like when he press a normal button) by change image. This is my code:
final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("IMAGE", "motion event: " + event.toString());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
imageView.setImageResource(R.drawable.button_hover);
}
case MotionEvent.ACTION_UP: {
imageView.setImageResource(R.drawable.button);
}
}
return false;
}
});
and this is xml
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="std_button"
android:src="@drawable/button" />
but it doesn't work. If i use only ACTION_DOWN event, image change as i want, What's wrong?
回答1:
Try add break; after each case,
And as giozh said inside onTouch i return always false, so touch event result always not consumed. Just put return true after each case statement.
回答2:
Make selector xml in drawable folder with content like this :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_green" android:state_pressed="true"/>
<item android:drawable="@drawable/ic_red"/>
</selector>
回答3:
for change on event press you can try this.....
final ImageView imagen = (Imagen) findViewById(R.id.imageViewX);
ImageView imagen = (ImageView)findViewById(R.id.imageViewX);
imagen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ImageView perse = (ImageView) findViewById(R.id.imageViewX);
perse.setImageResource(R.drawable.backgroundtwo);
}
});
来源:https://stackoverflow.com/questions/21404602/imageview-change-image-on-press-and-on-release