Witek Witek - 1 year ago 113
Android Question

Android ImageButton without border but still with click indication

How to create an ImageButton without border (just the image should be visible)? One could achieve this by setting

, but this also removes the focus and selection colors.

The goal is that initially only the image without borders is visible. But when the user focuses/touches/clicks the image this should be indicated by hightlighting the image like regular buttons.

Solution in Java-Code for API 14 is preferred. Thank you!

Answer Source

As has been mentioned, the borderlessButtonStyle built into the default themes on API11 and above is the simplest way to achieve this effect. You mentioned you are creating your buttons in Java code instead of XML, so there are two options depending on how you need to apply the style.

Option #1: Add it to the theme

If all the Button or ImageButton instances in your application (or at least within the Activity) need to have this style applied, add the styling to your theme instead:

    <style name="AppTheme" parent="android:Theme.Holo.Light">
        <!-- Default style for ImageButtons -->
        <item name="android:imageButtonStyle">?android:borderlessButtonStyle</item>
        <!-- Default style for Buttons -->
        <item name="android:buttonStyle">?android:borderlessButtonStyle</item>

With this theme applied to your Application or Activity, you won't have to declare the style of each element, you can just declare them as

Button button = new Button(context);
ImageButton imageButton = new ImageButton(context);

And the styling will be pulled from the theme.

Option #2: Declare it in the constructor

If only a couple buttons need to be styled this way, you can pass the style attribute you want to apply directly to each view, like so:

Button button = new Button(context, null, android.R.attr.borderlessButtonStyle);
ImageButton imageButton = new ImageButton(context, null, android.R.attr.borderlessButtonStyle);

This version supplies a different default style attribute for the widget to use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download