自定义的控件或布局,如何将属性传过去,本文以自定义textview为例,简单介绍一下。
1、首先创建一个类,MyTextView 继承TextView。
2、vaule 下新建一个xml文件,命名为attrs.xml。这里定义两个属性。一个是textsize 一个是textcolor
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="mytextview">
<attr name="textsize" format="dimension" />
<attr name="textcolor" format="reference|color"/>
</declare-styleable>
</resources>
3、在界面布局文件中,引入自定义的 MyTextView
<com.mobo.reading_androidapp.CEDetails.MyTextView
android:id="@+id/tv_cedetails_main_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
mytextview:textcolor="@color/gray"
mytextview:textsize="@dimen/txt_rem" />
最后两行为颜色和字体大小 属性,注意对应
4、在MyTextView 的构造方法中 获取布局中的属性,设置给控件
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
/ **你所传的属性,都在t中*/
TypedArray t = context.obtainStyledAttributes(attrs,
R.styleable.mytextview);
textSize = t.getDimension(R.styleable.mytextview_textsize, 24);
textColor=t.getColor(R.styleable.mytextview_textcolor, getResources().getColor(R.color.gray));
paint1.setTextSize(textSize);
paint1.setColor(textColor);
paint1.setAntiAlias(true);
paintColor.setAntiAlias(true);
paintColor.setTextSize(textSize);
paintColor.setColor(Color.BLUE);
}
其他重写方法省略。如有疑问可以留言哦。同时欢迎高手指点。