使用代码定义的shape资源类
public static Drawable getDrawable(int rgb, int radius){
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(rgb);
gradientDrawable.setGradientType(GradientDrawable.RECTANGLE);//矩形
gradientDrawable.setCornerRadius(radius);//四周圆角半径
gradientDrawable.setStroke(UIUtils.dp2px(1),rgb);//边框厚度与颜色
return gradientDrawable;
}
关键api方法:
setColor(rgb); //填充颜色
setGradientType(GradientDrawable.RECTANGLE); //shape矩形
setCornerRadius(radius); //四周圆角半径
setStroke(1,strokenColor); //边框厚度与颜色
用法:在代码中使用这个方法设置控件背景就OK了。
使用代码定义的selector选择器资源类
public static StateListDrawable getSelector(Drawable normalDrawable,Drawable pressDrawable){
StateListDrawable stateListDrawable = new StateListDrawable();
//给当前的颜色选择器添加选中图片选中指向状态,未选中图片指向状态
stateListDrawable.addState(new int[]{android.R.attr.state_enabled,android.R.attr.state_pressed},pressDrawable);
stateListDrawable.addState(new int[]{android.R.attr.state_enabled},normalDrawable);
//设置默认状态
stateListDrawable.addState(new int[]{},normalDrawable);
return stateListDrawable;
}
用法:
1.设置selector:
tv.setBackground( DrawableUtil.getSelector(DrawableUtil.getDrawable(Color.rgb(r, g, b), UIUtils.dp2px(5)),
DrawableUtil.getDrawable(Color.WHITE, UIUtils.dp2px(5))));
2.设置TextView的内边距:
int padding = UIUtils.dp2px(5);
tv.setPadding(padding, padding, padding, padding);
3.设置监听:
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(HotProductFragment.this.getActivity(), tv.getText(), Toast.LENGTH_SHORT).show();
}
});