自定义控件或布局如何传属性值

自定义的控件或布局,如何将属性传过去,本文以自定义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); 

其他重写方法省略。如有疑问可以留言哦。同时欢迎高手指点。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值