自定义命名空间与null命名空间:Android最佳实践

时间:2014-06-01 11:02:51

标签: android android-layout namespaces android-linearlayout xml-namespaces

在开发Android用户界面时,我应该定义自定义命名空间还是使用空命名空间?为什么?

作为一个具体的例子。请考虑以下事项:

自定义命名空间

布局/ main.xml中:

<com.example.MyExample
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.example"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    custom:customString="Test String"/> 

RES / attrs.xml:

<declare-styleable name="MyExample">
    <attr name="customString" format="string" />
</declare-styleable>

的src / COM /示例/ MyExample.java:

LayoutInflater.from(context).inflate(R.layout.my_example, this, true);   
((TextView)findViewById(R.id.textview)).setText(
    attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example", "customString")
);

空命名空间

布局/ main.xml中:

<com.example.MyExample
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    customString="Test String"/> 

的src / COM /示例/ MyExample.java:

LayoutInflater.from(context).inflate(R.layout.my_example, this, true);   
((TextView)findViewById(R.id.textview)).setText(
    attrs.getAttributeValue(null, "customString")
);

1 个答案:

答案 0 :(得分:0)

如果您有多个具有相同属性名称的库项目,则必须使用自定义命名空间。或者,如果您正在编写库项目,则应使用它们以防其他人使用相同的名称atrributes。否则,这取决于你,但建议。

相关问题