ImageView: change image on press, and on release

可紊 提交于 2019-12-24 11:56:28

问题


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

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