android 代码设置按钮(button)按下与弹起背景


1. 代码设置按钮基本参数

//获取布局
FrameLayout layout = findViewById(R.id.frame2);//(LinearLayout)findViewById(R.id.ll);

//获取按钮视图
View fra = LayoutInflater.from(this).inflate(R.layout.cos_button,null);
MyButton btn = fra.findViewById(R.id.custom_btn);

//设置按钮参数
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width,height);
params.leftMargin = 100;
params.topMargin = 100;
btn.setLayoutParams(params);


btn.setText("按钮");
//设置按钮标签,类型为Object
btn.setTag(1);
//设置标题大小(Float)
btn.setTextSize(13f);
//设置标题颜色
int color = ImageUtils.StringToColor(textColor);
btn.setTextColor(color);

//获取按钮不同状态的背景图片字符串,后再将字符串转成Bitmap
final String strNormalImage = ImageWithName.get(BackImage);
final String strPressImage = ImageWithName.get(PressImage);

2. 添加按钮的OnTouch事件响应(控件添加OnTouch事件后,OnClick事件就不会响应了)

 
 
btn.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        MyButton myBtn = (MyButton)v;
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP://松开事件发生后执行代码的区域
                Log.i(Tag,"点击按钮弹起事件");
                myBtn.setBackground(new BitmapDrawable(ImageUtils.StringToBitmap(strNormalImage)));
                break;
            case MotionEvent.ACTION_DOWN://按住事件发生后执行代码的区域
                Log.i(Tag,"按下按钮事件");
                myBtn.setBackground(new BitmapDrawable(ImageUtils.StringToBitmap(strPressImage)));
                
                break;
            default:
                break;
        }

        return true;
    }
});

3. Image工具类

public class ImageUtils {


    public static  Bitmap StringToBitmap(String string){
        //将字符串转换成Bitmap类型
        Bitmap bitmap=null;
        try {
            byte[]bitmapArray;
            bitmapArray= Base64.decode(string, Base64.DEFAULT);
            bitmap= BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     *
     * @param string 颜色字符串
     * @return  颜色
     */
    public  static int StringToColor(String string) {
        String[] ARGB = string.split(":");
        int Alpha = Integer.parseInt(ARGB[0]);
        int Red = Integer.parseInt(ARGB[1]);
        int Green = Integer.parseInt(ARGB[2]);
        int Blue = Integer.parseInt(ARGB[3]);

        return Color.argb(Alpha,Red,Green,Blue);
    }
}


猜你喜欢

转载自blog.csdn.net/amberoot/article/details/79855131