天天看點

android 自定義 xml 屬性

按照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了,按照教程的建議吧,雖然命名規則可能比較寬松.