参考:http://blog.csdn.net/lmj623565791/article/details/24252901
步骤:
1)在res/value /attrs 下 定义view的属性
<declare-styleable name="CustomNumberView">
<attr name="viewIcon" format="reference|color" />
<attr name="iconHeight" format="dimension"/>
<attr name="numberText" format="string"/>
</declare-styleable>
2)在使用到这个view的xml布局中使用:
在CustomVIew extends View 的构造函数里:
在3个构造函数里获取自定义的属性,因为加载XML 布局,是走2个参数的构造函数的,所以在2构造参数里 调用3个构造参数即可。
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/**
* 加载布局时 获取自定义的属性
* 默认走 2个参数的构造函数,所以这里加载后 让2参数去调用它
* obtainStyledAttributes(int resId,int[] attrs) //从资源文件定义的style中读取属性
*/
TypedArray aLq= context.obtainStyledAttributes(attrs,R.styleable.CustomView);
aLq.getString(R.styleable.CustomView_lq_text);
View view = LayoutInflater.from(context).inflate(R.layout.view_custom,this,true);
TextView tvName =(TextView)view.findViewById(R.id.tvName);
TextView tvNumber =(TextView)view.findViewById(R.id.tvNumber);
String textName= aLq.getString(R.styleable.CustomView_lq_text);
Log.d(TAG, "CustomView: textName " +textName);
tvName.setText(textName);
// tvName.setBackgroundResource(aLq.getResourceId(R.styleable.CustomView_lq_background,R.drawable.number_bg));
ViewGroup.LayoutParams params =(LayoutParams)tvName.getLayoutParams();
int width=aLq.getDimensionPixelOffset(R.styleable.CustomView_lqW,20);
int height = aLq.getDimensionPixelOffset(R.styleable.CustomView_lqH,20);
params.height=height;
params.width=width;
Log.d(TAG, "CustomView: h= " +height +" width =" +width);
tvName.setLayoutParams(params);
aLq.recycle();
}
我心境如止水 杀不死我的 都会让我强大
网友评论