加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

自定义的组件xml属性

发布时间:2020-12-15 23:27:52 所属栏目:百科 来源:网络整理
导读:对于自定义的组件,不仅可以利用view自带的xml属性进行布局控制还可以通过自定义xml属性的方式实现对view的控制。 一般写xml属性时android:****的格式,其中的android是命名空间,关于什么是命名空间,这不是本文讨论的范围。一般来说,在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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读