ImageButton doesn't highlight on click with Transparent background

前端 未结 4 1770
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 00:00

I\'ve set up an ImageButton to be transparent, so the icon matches the backgrond panel like the Android ActionBar. This looks fine as I want it to.

However, when the

相关标签:
4条回答
  • 2020-12-05 00:29

    If you want to do it programmatically, here is one solution:

    Create a custom ImageButton class and Override drawableStateChange():

    public class CustomImageButton extends ImageButton {
    
        @Override
        protected void drawableStateChanged() {
            Log.d("Button", "isPressed: " + isPressed() );
            if( isPressed() ){
                setBackgroundResource( android.R.color.holo_blue_dark );
            }  else {
                setBackgroundResource( android.R.color.transparent );
            }
            super.drawableStateChanged();
    
        }
    
        public CustomImageButton( Context context ) {
            super( context );
        }
    
        public CustomImageButton( Context context, AttributeSet attrs ) {
            super( context, attrs );
        }
    
        public CustomImageButton( Context context, AttributeSet attrs, int defStyle ) {
            super( context, attrs, defStyle );
            // TODO Auto-generated constructor stub
        }
    
    
    
    }
    
    0 讨论(0)
  • 2020-12-05 00:31

    All you need to do is to set the proper background. If you want it to be transparent in normal state and blueish in pressed stated.

    Create a StateListDrawable like this one in res/drawable directory.

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/my_bluish_color" android:state_pressed="true"/>
        <item android:drawable="@android:color/transparent"/>
    </selector>
    

    This way the default background is transparent. When pressed the background has the color you specified (instead of color you can use any drawable here).

    0 讨论(0)
  • 2020-12-05 00:31

    I came across this same problem. Finally, I got a sample of a code with that attribute:

    android:background="?android:selectableItemBackground"
    

    This attibute will give a transparent background with selectable highlight to any View (Button, ImageButton, TextView...) WITHOUT MORE CODING!!!

    0 讨论(0)
  • 2020-12-05 00:39

    Just to add on Fernandez good answer:

    If you want the effect to be Round and not rectangle use:

    android:background="?android:selectableItemBackgroundBorderless"    
    

    (*for V21 and up).

    0 讨论(0)
提交回复
热议问题