自定义的组件xml属性


对于自定义的组件,不仅可以利用view自带的xml属性进行布局控制还可以通过自定义xml属性的方式实现对view的控制。

一般写xml属性时android:****的格式,其中的android是命名空间,关于什么是命名空间,这不是本文讨论的范围。一般来说,在xml文件的根部我们都会加上xmlns:android="http://schemas.android.com/apk/res/android",这其实是android定义好的命名空间。因此如果直接在xml文件里写 myxmlns:hello="hello" 那么编译器就会报错,首先把myxmlns当做一个命名空间了,而该命名空间是不存在的,所以会报错。解决办法是首先在view树的根部声明命名空间。

如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myxmlns="http://schemas.android.com/apk/res/com.test.xml"
android:id="@+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />


这里的红色字体部分是我声明的命名空间。当用自定义命名空间时一般的格式为:http://schemas.android.com/apk/res/ “ + ” 应用的包名( 注意,这里应用的包名是:com.test.xml )

当定义完命名空间后,编译器仍会报错,这是由于没有为命名空间配置属性,也就是说该空间内的取值现在是不确定的。
解决办法如下:

在values文件加下新建xml文件进行如下配置:

<?xml version="1.0" encoding="utf-8"?><resources>
    <declare-styleable name="MyView">
        <attr name="text" format="string" />
    </declare-styleable>
</resources>



这里的 declare-styleable name="MyView" 是为了获取我们在xml中自定义配置属性的值而设置的一个标志符

而后就可以在xml里面使用该属性了:

如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myxmlns="http://schemas.android.com/apk/res/com.test.xml"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<com.test.xml.MyView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/my_view"
    myxmlns:text="hello_world!">
</com.test.xml.MyView>

 </LinearLayout>



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

q1121674367

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值