创建自定义控件在布局中的自定义属性

1.在values目录下新建attrs.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MusicView">
<attr name="height1" format="integer" />
</declare-styleable>
</resources>


height1就是我们的自定义属性

2.在布局文件中创建自定义控件


<demo.com.selfdefineview.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
music:height1="100"
/>


这个时候是无法编译通过的,music属性会报红,这是因为没有找到music命名空间的缘故,所以我们要自己要加一个命名空间,在布局文件的第一个元素内,加上


xmlns:music="http://schemas.android.com/apk/res/demo.com.selfdefineview"


加上后,编译就可以通过,最后一段是包名

3.新建一个类MyView



public class MyView extends View {

public MyView(Context context){
super(context);
}

public MyView(Context context, AttributeSet attrs){

super(context,attrs);


TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.MusicView);
int aa = ta.getInteger(R.styleable.MusicView_height1,0);


Toast.makeText(context,"aa="+aa,Toast.LENGTH_LONG).show();

}
}



运行,此时可以看到toast提示aa=100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值