attrs属性问题
attrs.xml设定的自定义属性,指的是在xml布局中使用的 android:text="" 等属性。
第一步:
一、在res/values文件下定义一个attrs.xml文件.代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="flow">
<attr name="textColor" format="color"/>
</declare-styleable>
</resources>
二:使用自定义属性,就需要有这么一个构造函数
private final static int H_DISTANCE = 20;
private final static int V_DISTANCE = 20;
private View childAt;
private int color;
public MyClass(Context context) {
super(context);
}
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.flow);
color = array.getColor(R.styleable.flow_textColor, 0);
}
public MyClass(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//创建添加方法
public void addView(final String keys) {
//创建布局
final String s = keys.toString();
TextView textview = (TextView) View.inflate(getContext(), R.layout.item, null);
textview.setText(s);
textview.setTextColor(color);
LayoutParams layoutParams = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutParams);
addView(textview);
}
主要是: 使用自定义属性,就需要有这么一个构造函数.所以context.obtainStyledAttributes((attrs,R.styleable.flow) ;得到那个array数组
<R.styleable.flow 是 读取attrs中参数名,是以“样式名_参数名”的形式;>
color = array.getColor(R.styleable.flow_textColor, 0);
textview.setTextColor(color); 设置颜色就好了<字体大小都类似…>
<---------------------------------------------attrs.xml中的写法-------------------------------------------------------->
三:<MainActivity.xml布局中的写法>
自定义类中直接添加属性
四:效果展示