习惯了用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);