android 自定义 xml 属性

来源:互联网 发布:java外部接口 编辑:程序博客网 时间:2024/06/05 11:31

按照http://www.cnblogs.com/kross/p/3458068.html

以及

http://gundumw100.iteye.com/blog/1040917

尝试了一把自定义xml tag, 很简单,按部就班来就基本不会有问题,

在最后一步犯2了,在引入自己新的自定义的xmlns时,应该在使用了自定义VIew的layout xml文件中使用,而不是在 自定义view本身的layout xml文件中使用,

因为自定义的xml属性是对外的,那么自然设置以及引入相应的命名空间要在使用了自定view的layout文件中,自定义xml属性的设置也是在使用了自定义view的

layout文件中,而不是自定义view自己的layout文件。

还要注意的是       获取里面属性用 "名字_ 属性" 连接起来, declare-styeable 意思就是将这一坨attr 包在 一个 叫 MyLinearLayout的 styleable中。

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="MyLinearLayout">        <attr name="My_src" format="reference"/>        <attr name="My_text" format="string"/>    </declare-styleable></resources>

那么在定义view的code里:

switch (attrName) {            case R.styleable.MyLinearLayout_My_src:            mImageView.setImageResource(            attrArray.getResourceId(R.styleable.MyLinearLayout_My_src, R.drawable.ic_launcher));            break;            case R.styleable.MyLinearLayout_My_text:            mTextView.setText(attrArray.getString(R.styleable.MyLinearLayout_My_text));            break;            }
注意从R.styleable.中使用自定义属性时,要前面加  类名_
其实从生成的R.java文件也可以看出来。

真正在xml使用中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:fyf="http://schemas.android.com/apk/res/com.example.fyf"    android:id="@+id/root"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical">    <Button        android:id="@+id/inval"        android:text="Refresh"        android:layout_width="wrap_content"    android:layout_height="wrap_content"/>    <com.example.fyf.SimpleView        android:id="@+id/simple"        android:background="@drawable/bender03pb"        android:layout_width="50dp"    android:layout_height="50dp"/>    <com.example.fyf.MyLinearLayout        android:id="@+id/myLinear"        android:layout_width="500dp"        android:layout_height="500dp"        fyf:My_text="MY TEXT VIEW"        fyf:My_src="@drawable/bender03pb"</LinearLayout>

注意自定义的所有namesapce和属性都是在使用了 自定义View 的 layout文件中设置, 而不是在 自定义View 自己本身的layout 文件中。

至于 attrs.xml中的命名规则,懒得try了,按照教程的建议吧,虽然命名规则可能比较宽松.

0 0
原创粉丝点击