• 利用StateListDrawable给button动态设置背景


    项目中,遇到相同样式的Button,只是stroke颜色不一样。为了实现一个,就得写两个shape文件,一个selector文件;多个还得重复写。

     解决方法:

    结合StateListDrawable给button动态设置背景

        public void initButton() {
            GradientDrawable fDrawable = (GradientDrawable) getResources().getDrawable(R.drawable.circle_button);
            fDrawable.setColor(Color.RED);
            fDrawable.setStroke(4, Color.BLUE);
            GradientDrawable nDrawable = (GradientDrawable) getResources().getDrawable(R.drawable.circle_button);
            nDrawable.setColor(Color.YELLOW);
            nDrawable.setStroke(4, Color.GREEN);
            StateListDrawable drawable = new StateListDrawable();
            drawable.addState(new int[]{android.R.attr.state_pressed}, fDrawable);
            drawable.addState(new int[0], nDrawable);
            myButton.setBackgroundDrawable(drawable);
        }

    XML文件

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
    
        <solid android:color="#f2f2f2" />
        <stroke
            android:width="4px"
            android:color="#000000" />
        <corners android:radius="100dp" />
    
    </shape>

    这样,对于相同样式,不同颜色的Button,就不需要再去重复写多个XML文件了,一个文件确定样式就搞定

  • 相关阅读:
    考研系列一-线性表类(顺序存储)
    因特网协议分层及它们的服务模型
    矩阵归零
    字符编码(续)---Unicode与ANSI字符串转换以及分辨字符编码形式
    奇妙的位运算
    一道面试题Lintcode196-Find the Missing Number
    错误处理
    px 和 em 的区别
    简述同步和异步的区别
    简述一下 src 与 href 的区别
  • 原文地址:https://www.cnblogs.com/wenhui92/p/7135592.html
Copyright © 2020-2023  润新知