在xml中设置视图的自定义属性。

在xml中写出自定义的属性值方法。

实例:在xml中给自定义布局写出自定义属性的值。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <com.zq.androidservice.dialog.SelfView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:text="aaaa"
        app:background_color="@color/blue"
       />

  xmlns:app="http://schemas.android.com/apk/res-auto" 这一句话是用来命名空间的。前面的app可以随便改成任何你想要的自定义的名字。



1.首先需要你在values的styles中写你想要的属性与属性命名,与你给这些属性集合的命名。(这里是SelfView)

<resources>
 
   <declare-styleable name="SelfView">

        <attr name="background_color" format="color"/>
        <attr name="text" format="string"/>

    </declare-styleable>

</resources>

然后需要你在自定义视图的.java文件中获取绑定,调用AttributeSet的属性获取对应的你在value
private void init(Context context,AttributeSet attrs){
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.SelfView);
        int mColor = ta.getColor(R.styleable.SelfView_background_color, Color.BLACK);
        String mTextStr = ta.getString(R.styleable.SelfView_text );
        ta.recycle();  //注意回收
        Log.e("SelfView_text","SelfView_text = " + mTextStr);
    }

注意:此方法是需要你自定去手写,在自定义视图的构造器中去调用。获取到你在xml中设置的属性值,然后根据你的需求,做出相对应的处理。

绑定属性时,先是通过属性集的名字,获取属性集。然后是以属性集的名字做前缀,带下划线的形式,接上属性名,获取对应属性值。

之后获取到的属性值拿去做你想做的处理。


至此完毕~

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值