How can I give an imageview click effect like a button on Android?

前端 未结 30 2270
情歌与酒
情歌与酒 2020-11-28 01:50

I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clic

30条回答
  •  再見小時候
    2020-11-28 02:07

    EDIT: Although the original answer below works and is easy to set up, refer to this post by an Android Developer Advocate at Google if you want / need a more efficient implementation. Also note that the android:foreground attribute is coming to all Views, including ImageView, by default in Android M.


    The problem with using a selector for an ImageView is that you can only set it as the view's background - as long as your image is opaque, you will not see the selector's effect behind it.

    The trick is to wrap your ImageView in a FrameLayout with the attribute android:foreground which allows us to define an overlay for its content. If we set android:foregroundto a selector (e.g.?android:attr/selectableItemBackground for API level 11+) and attach the OnClickListener to the FrameLayout instead of the ImageView, the image will be overlaid with our selector's drawable - the click effect we desire!

    Behold:

    
    
        
    
    
    

    (Note this should be placed within your parent layout.)

    final View imageButton = findViewById(R.id.imageButton);
    imageButton.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            // do whatever we wish!
        }
    });
    

提交回复
热议问题