实现按钮的点击效果,往往需要两张图片,但是图片多了,项目就变得很大了,为了减少图片的目的,只需要用一张图片来实现点击的效果。查了一些资料,可以通过改变当前按钮背景的亮度,来实现这一效果。可能有更好的办法实现。
public static StateListDrawable getStateListDrawable(Drawable normal) { StateListDrawable listDrawable = new StateListDrawable(); Bitmap srcBitmap = ((BitmapDrawable) normal).getBitmap(); Bitmap bmp = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Config.ARGB_8888); int brightness = 60 - 127;// 改变亮度 ColorMatrix cMatrix = new ColorMatrix(); cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness, 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 }); Paint paint = new Paint(); paint.setColorFilter(new ColorMatrixColorFilter(cMatrix)); Canvas canvas = new Canvas(bmp); // 在Canvas上绘制一个Bitmap canvas.drawBitmap(srcBitmap, 0, 0, paint); Drawable pressed = new BitmapDrawable(bmp); listDrawable.addState(new int[] { android.R.attr.state_pressed }, pressed); listDrawable.addState(new int[] { android.R.attr.state_selected }, pressed); listDrawable.addState(new int[] { android.R.attr.state_enabled }, normal); return listDrawable; }
只需设置按钮的setBackgroundDrawable(getStateListDrawable(XX));调用上面的方法就行了。
点击前效果
点击后效果