2

通常,自定义属性的示例采用以下形式:

<declare-stylable name="MyView">
    <attr name="name" format="string"/>
</declare-styleable>  

及其用法:

<com.example.test.MyView
    customns:name="Hello"/>

因此自定义视图与可样式化属性具有相同的名称。

但是在这个例子中(点击查看完整代码)你会看到:

<declare-styleable name="Options">
    <attr name="titleText" format="string" localization="suggested" />
    <attr name="valueColor" format="color" />
</declare-styleable>

使用者:

<com.vogella.android.view.compoundview.ColorOptionsView
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    custom:titleText="Background color"
    custom:valueColor="@android:color/holo_green_light"
    />

这让我想知道,它是如何ColorOptionsView与 name 定义的属性相关联的Options

4

1 回答 1

1

Those options are available as part of the declared namespace custom, which is included at the top of the XML file:

xmlns:custom="http://schemas.android.com/apk/res/com.vogella.android.view.compoundview"

NOTE

Simply adding this line will not provide support for auto-complete. If that is what your mean by your question, you need to add the schema to your workspace's XML Catalog. You can do this in Eclipse by going to Eclipse -> Preferences, then XML -> XML Catalog. Here, click the Add... button. Navigate to the XML Schema file, then select OK. If you close and re-open the the XML file, you will now have autocompletion.


Finally, when unpacking the attributes used in ColorOptionsView.java, the author can specifically look for attributes from this namespace. This is from the same source (commented by me):

//grab the declared-styleable resource entries
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Options, 0, 0);
//get the "titleText" entry from this element's attributes
String titleText = a.getString(R.styleable.Options_titleText);
//get the "valueColor" attribute. If it does not exists, set the default to holo_blue_light
int valueColor = a.getColor(R.styleable.Options_valueColor,
    android.R.color.holo_blue_light);
a.recycle();
于 2013-04-22T18:27:03.440 回答