Android自定义一个多状态按钮

Home / Android MrLee 2015-8-3 3798

现在的移动APP数量繁多,为了提高自己的APP吸睛率,策划和开发人员可以说都是绞尽脑汁玩出新花样。本控件也是为了满足项目需求,特此放上来方便大家及以后自己使用。
这个多功能按钮主要功能是有多个状态,不同状态显示不同的图片,并且还带有闪烁的效果。下面是图和代码。

multibutton


package com.androiddemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
/**
 * 多功能按钮,各种状态
 * 
 * @author leehom
 * 
 */
public class MultiButton extends ImageView {
	private Bitmap[] bitmaps;
	private int index;// 当前状态
	private AlphaAnimation alphaAnimation;
	public MultiButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
	public void startAnimation() {
		if (alphaAnimation == null) {
			alphaAnimation = new AlphaAnimation(0, 1);
			alphaAnimation.setRepeatCount(Animation.INFINITE);
			alphaAnimation.setRepeatMode(Animation.REVERSE);
			alphaAnimation.setDuration(500);
		}
		startAnimation(alphaAnimation);
	}
	public void stopAnimation() {
		if (alphaAnimation != null)
			alphaAnimation.cancel();
		if (getAnimation() != null)
			getAnimation().cancel();
		setAnimation(null);
	}
	public void prepIndex() {
		int tempIndex = index;
		--tempIndex;
		if (tempIndex >= 0 && tempIndex < bitmaps.length)
			index = tempIndex;
		else if (bitmaps != null)
			index = bitmaps.length - 1;
		postInvalidate();
	}
	public void nextIndex() {
		int tempIndex = index;
		++tempIndex;
		if (tempIndex >= 0 && tempIndex < bitmaps.length)
			index = tempIndex;
		else
			index = 0;
		postInvalidate();
	}
	public void initBitmap(int[] ids) {
		bitmaps = new Bitmap[ids.length];
		for (int i = 0; i < ids.length; i++) {
			bitmaps[i] = BitmapFactory.decodeResource(getResources(), ids[i]);
		}
		ViewGroup.LayoutParams params = getLayoutParams();
		if (params != null && bitmaps != null && bitmaps[0] != null) {
			params.width = bitmaps[0].getWidth();
			params.height = bitmaps[0].getWidth();
			requestLayout();
		}
	}
	@Override
	public void draw(Canvas canvas) {
		// TODO Auto-generated method stub
		if (bitmaps != null && index >= 0 && index < bitmaps.length) {
			canvas.drawBitmap(bitmaps[index], 0, 0, null);
		}
	}
}

本文链接:https://www.it72.com/3934.htm

推荐阅读
最新回复 (0)
返回