`

Android Button background image pressed/highlighted and disabled states without

阅读更多

http://shikii.net/blog/android-button-background-image-pressedhighlighted-and-disabled-states-without-using-multiple-images/

 

In Android, if you provide custom background images for buttons, you will lose the pressed and disabled image effects. The common way to fix that is to provide additional images for those states. I’m lazy and I find this inconvenient especially during the prototyping phase of app development.

I’ve always liked the way iOS automatically handles pressed and disabled states for custom button backgrounds so I made a Button subclass that automatically darkens the background image when the button is pressed, and makes the background transparent when it is disabled. This is done by using a custom LayerDrawable for the button that contains the original background Drawable . The LayerDrawable has to be stateful and should change the background properties depending on the current state in onStateChange() . The full source explains it better:

 

package net.shikii.widgets;

import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Applies a pressed state color filter or disabled state alpha for the button's background
 * drawable.
 *
 * @author shiki
 */
public class SAutoBgButton extends Button {

  public SAutoBgButton(Context context) {
    super(context);
  }

  public SAutoBgButton(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public SAutoBgButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public void setBackgroundDrawable(Drawable d) {
    // Replace the original background drawable (e.g. image) with a LayerDrawable that
    // contains the original drawable.
    SAutoBgButtonBackgroundDrawable layer = new SAutoBgButtonBackgroundDrawable(d);
    super.setBackgroundDrawable(layer);
  }

  /**
   * The stateful LayerDrawable used by this button.
   */
  protected class SAutoBgButtonBackgroundDrawable extends LayerDrawable {

    // The color filter to apply when the button is pressed
    protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
    // Alpha value when the button is disabled
    protected int _disabledAlpha = 100;

    public SAutoBgButtonBackgroundDrawable(Drawable d) {
      super(new Drawable[] { d });
    }

    @Override
    protected boolean onStateChange(int[] states) {
      boolean enabled = false;
      boolean pressed = false;

      for (int state : states) {
        if (state == android.R.attr.state_enabled)
          enabled = true;
        else if (state == android.R.attr.state_pressed)
          pressed = true;
      }

      mutate();
      if (enabled && pressed) {
        setColorFilter(_pressedFilter);
      } else if (!enabled) {
        setColorFilter(null);
        setAlpha(_disabledAlpha);
      } else {
        setColorFilter(null);
      }

      invalidateSelf();

      return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
      return true;
    }
  }

}

 

To use this, just replace your original button declarations like this:

<Button
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:background="@drawable/button_blue_bg"
  android:text="Button with background image" />
 

To this:

<net.shikii.widgets.SAutoBgButton
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:background="@drawable/button_blue_bg"
  android:text="Button with background image" />
 

Here’s a sample output using this custom button:

The code is also available on GitHub .

 

 

Reference:

http://stackoverflow.com/questions/6705304/how-to-set-alpha-value-for-drawable-in-a-statelistdrawable

 

分享到:
评论

相关推荐

    Android Selector和Shape的使用方法

    1.背景选择器(位于res/drawable/,使用方法:android:background=”@drawable/XXX”) 代码如下: &lt;?xml version=”1.0″ encoding=”utf-8″?&gt; &lt;selectorxmlns android=”...

    button-is-pressed

    按键按下判断,3种方法都可行,适用于薄膜按钮\手柄按键\脚踏按键

    Android编程实现改变控件背景及形态的方法

    本文实例讲述了Android编程实现改变控件背景及形态的方法。分享给大家供大家参考,具体如下: 1. 改变背景 ...item android:state_pressed=true android:drawable=@drawable/search_bar_edit_pressed /

    自定义SeekBar样式

    &lt;item android:state_pressed="true" android:drawable="@drawable/bg3" /&gt; &lt;!-- 普通无焦点状态 --&gt; &lt;item android:state_focused="false" android:state_pressed="false" android:drawable="@drawable/bg" /&gt;...

    Android实现简易版弹钢琴效果

    本文实例为大家分享了Android实现弹钢琴效果展示的具体代码,供大家参考,具体内容如下 ... &lt;item android:drawable=@drawable/button_pressed android:state_pressed=true&gt;&lt;/item&gt; &lt;item android

    Android 自定义Button控件实现按钮点击变色

    效果图如下所示: 一、shape 样式:(在drawable新建–》new–》Drawable resource file 在父级标签...&lt;item android:state_pressed=true&gt; &lt;shape android:shape=rectangle&gt; &lt;solid android:color=#73c4f3&gt; &lt;

    Android代码-云标签控件

    Editable Style of Tag, Background/Pressed Color, Radius effect, Custom Background, Delete mode. Listener of tag selecting and deleting. Can be created from XML file or Java code. Sample A

    Android代码-Senior Launcher

    It registers as app launcher (that means it is called when the phone boots and the home button is pressed). It let's the user decide if he wants to call someone or wants to watch images It reads the ...

    Android代码-camera-touch-button

    Keep the button pressed to open the camera release the button to capture the photo :) This library uses CameraKit-Android Demo Install Add the dependecy in build.gradle(module: app) repositories {...

    Android开发实现的圆角按钮、文字阴影按钮效果示例

    本文实例讲述了Android开发实现的圆角按钮、文字阴影按钮效果。分享给大家供大家参考,具体如下: ... &lt;item android:state_pressed=true&gt; &lt;shape xmlns:android=http://schemas.android.com/apk/res/

    note-player-stream:根据输入流使用 Web Audio API 播放不同的音符

    pressed : Boolean , // Whether the button has been pressed/released note : Number , // Integer between [0-127] which represents a midi note frequency : Number , // The frequency to play the ...

    Android编程使用自定义shape实现shadow阴影效果的方法

    本文实例讲述了Android编程使用自定义shape实现shadow阴影效果的方法。... &lt;item android:state_pressed=true&gt; &lt;layer-list&gt; &lt;!-- 相当于padding --&gt; &lt;item android:left=4dp android

    Android代码-TagView

    Android TagView Android TagView-HashTagView Xamarin version, written by @fernandolopes ...Simple android view to ...Editable Style of Tag, Background/Pressed Color, Radius effect, Custom Background, Del

    Android代码-FloatingActionButton

    WARNING! FURTHER DEVELOPMENT AND SUPPORT IS DISCONTINUED. FloatingActionButton Yet another implementation of Floating Action Button for Android with ...Option to set custom normal/pressed/ripple colors

    高仿微信界面

    android:background="@drawable/home_pressed" android:clickable="false" /&gt; android:id="@+id/tv_page_home" android:textColor="#ffd100" android:layout_width="wrap_content" android:layout_height=...

    flyd-sampleon:Flyd 的 sampleOn

    // Assume `sendBtnClicked` emits whenever a send button is pressed and // `messageText` is a stream of the current content of an input field. // Then `sendMessage` emits the content of the text field...

    Android ImageView的selector效果实例详解

    在平时开发中如Button我们给它加上selector分别呈现pressed以及normal效果能给我们的用户体验上大大增色不少,可是我们当我们是用ImageView来”当作”一个一个”Button”的时候发现直接设置selector却不起作用,当然...

    一个 React Native 模块,用于在 Android 上捕获您的主页和最近的应用按钮

    react-native-home-pressed 入门 $ npm install react-native-home-pressed --save 自动安装(无需进一步设置) $ react-native link react-native-home-pressed 手动安装 Android 打开 android/app /src/main/java/...

    MSP430G系列触摸参考代码

    MSP430G系列带触摸参考代码, Basic 8-button input using the built-in pin ...// After each scan, one UART byte identifying the key# being pressed is // transmitted via TimerA UART at port pin P1.1.

    Android中的Selector的用法详解及实例

    Android中的Selector的用法  ... &lt;item android:state_pressed=true android:drawable=@drawable/bg_selected&gt; &lt;/item&gt; &lt;item android:drawable=@drawable/bg_unselect&gt; &lt;/item&gt; &lt;/selector&gt;  在

Global site tag (gtag.js) - Google Analytics