我已經擴展ViewGroup並在Android中創建了自定義佈局類。我還定義了一些自定義XML屬性以幫助定位子視圖。我需要訪問根XML元素(自定義佈局)上的一些自定義xml屬性(custom:view_height和custom:view_width),但是當我嘗試從Layout java類訪問它們時,TypedArray爲null,就像它看不到他們。他們在孩子的意見上工作得很好。有關如何從根中訪問自定義XML屬性的任何想法?謝謝!從根元素訪問自定義XML屬性
見代碼:
<?xml version="1.0" encoding="utf-8"?>
<package.of.my.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent" android:layout_width="match_parent"
android:orientation="vertical"
android:background="@drawable/homecell_selector"
custom:view_width="400" // I need this!!
custom:view_height="200" // I need this!!
>
<Button android:id="@+id/postText" android:layout_marginLeft="20dp"
android:layout_marginTop="45dp" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:alpha="1"
android:background="@color/HEX_FFFFFFFF" android:textColor="@color/HEX_000"
android:textSize="15sp" android:visibility="visible" android:gravity="left"
custom:view_width="0.87610022270753"
custom:eHeight="true"
custom:view_height="0.44296926842493"
custom:eWidth="true"
custom:originX="RIGHT"
custom:x="0.061399777292469"
custom:eX="true"
custom:originY="BOTTOM"
custom:y="0.1682145166653"
custom:eY="true"/>
<Button android:id="@+id/firstNameLastNameShortText" android:layout_marginLeft="21dp"
android:layout_marginTop="8dp" android:layout_height="18dp"
android:layout_width="276dp" android:alpha="1"
android:background="@color/HEX_2087fc" android:textColor="@color/HEX_000"
android:textSize="15sp" android:visibility="visible" android:gravity="left"
custom:view_width="0.86433765030597"
custom:eHeight="true"
custom:view_height="0.15716154473749"
custom:eWidth="true"
custom:originX="LEFT"
custom:x="0.065625" custom:eX="true"
custom:originY="TOP"
custom:y="0.069849575438883"
custom:eY="true"/>
</package.of.my.CustomLayout>
您如何試圖訪問您的自定義屬性?你能發佈代碼嗎? – alanv 2014-10-17 21:48:23
'TypedArray properties = myContext.obtainStyledAttributes(attrs,package.of.my.project.R.styleable.Custom); view_height = properties.getFloat(package.of.my.project.R.styleable.Custom_view_height,view_height);' 但屬性爲空。 – 2014-10-17 23:28:59
TypedArray爲空,就像你在帖子中說的,或者getFloat()返回默認值?另外,你是從你的CustomLayout的構造函數還是其他地方調用它? – alanv 2014-10-18 00:14:41