android中控件属性往往,详解Android自定义控件属性

在android开发中,往往要用到自定义的控件来实现我们的需求或效果。在使用自定义

控件时,难免要用到自定义属性,那怎么使用自定义属性呢?

在文件res/values/下新建attrs.xml属性文件,中定义我们所需要的属性。

public class customtextview extends textview {

private int textsize;//自定义文件大小

private int textcolor;//自定义文字颜色

//自定义属性,会调用带两个对数的构造方法

public customtextview(context context, attributeset attrs) {

super(context, attrs);

typedarray ta = context.obtainstyledattributes(attrs, r.styleable.custom_view);//typedarray属性对象

textsize = ta.getdimensionpixelsize(r.styleable.custom_view_custom_size, 20);//获取属性对象中对应的属性值

textcolor = ta.getcolor(r.styleable.custom_view_custom_color, 0x0000ff);

setcolorandsize(textcolor, textsize);//设置属性

ta.recycle();

}

public customtextview(context context) {

super(context);

}

private void setcolorandsize(int textcolor, int textsize) {

settextcolor(textcolor);

settextsize(textsize);

}

}

xmlns:tools="http://schemas.android.com/tools"

xmlns:ldm="http://schemas.android.com/apk/res/com.ldm.learn"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#f6f6f6"

android:orientation="vertical"

android:padding="10dp" >

android:layout_width="100dp"

android:layout_height="100dp"

android:text="自定义textview"

ldm:custom_color="#333333"

ldm:custom_size="35sp" />

布局说明:

2c7407dd2fe7bd0050768337610fa192.png

通过以上几步就可以实现我们想要的自定义属性效果(用自定义属性设置文字大小及颜色)啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值