手撕代码之java代码实现selector和shape

习惯了用xml布局的方式设置颜色、图片的选择器,有的时候需要跟灵活的动态设置,这个时候就会想到用代码直接实现,下面分享一下。

一、设置color选择器

color对应的是ColorStateList

一般用xml实现如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/color_666666" android:state_selected="false" />
    <item android:color="@color/color_999999" android:state_selected="true" />
</selector>

用代码实现如下:

        int[] colors = new int[]{0xff999999, 0xff666666};//对应分别对应states[0][],states[1][]
        int[][] states = new int[2][];
        states[0] = new int[]{android.R.attr.state_selected};//设置选择
        states[1] = new int[]{};
        ColorStateList defaultTextColorSelector = new ColorStateList(states, colors);
        textView.setTextColor(defaultTextColorSelector);

二、设置drawable选择器

 

drawable对应的是StateListDrawable

一般xml实现如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_bottom_tab1_unselected" android:state_selected="false" />
    <item android:drawable="@drawable/icon_bottom_tab1_selected" android:state_selected="true" />
</selector>

 

用代码实现如下:

 

        StateListDrawable mBgStateListDrawable = new StateListDrawable();
        mBgStateListDrawable.addState(new int[]{android.R.attr.state_selected}, getResources().getDrawable(R.drawable.icon_bottom_tab1_selected));
        mBgStateListDrawable.addState(new int[]{-android.R.attr.state_selected}, getResources().getDrawable(R.drawable.icon_bottom_tab1_unselected));

        final TextView textView = findViewById(R.id.hello);
        textView.setBackgroundDrawable(mBgStateListDrawable);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setSelected(!textView.isSelected());
            }
        });

需要注意添加state是有序的,会按顺序判断最先符合条件的state,如果把最大范围的state放在最前面,后面的将不会执行,此外,在添加state中,在state前添加“-”号,表示此state为false(例如:-android.R.attr.state_selected),否则为true。

三、代码设置shape

 

        int strokeWidth = 5; // 3dp 边框宽度
        int roundRadius = 15; // 8dp 圆角半径
        int strokeColor = Color.parseColor("#2E3135");//边框颜色
        int fillColor = Color.parseColor("#DFDFE0");//内部填充颜色

        GradientDrawable gd = new GradientDrawable();//创建drawable
        gd.setColor(fillColor);
        gd.setCornerRadius(roundRadius);
        gd.setStroke(strokeWidth, strokeColor, 30, 15);
        gd.setShape(GradientDrawable.OVAL);

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值