【问题标题】:Custom namespace vs. null namespace: Android best practice自定义命名空间与空命名空间:Android 最佳实践
【发布时间】:2014-07-21 15:56:51
【问题描述】:

在开发 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/example/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/example/MyExample.java:

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

【问题讨论】:

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


    【解决方案1】:

    如果您有多个具有相同属性名称的库项目,则需要自定义命名空间。或者,如果您正在编写一个库项目,您应该使用它们以防其他人使用相同的命名属性。否则由您决定,但建议使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2010-10-03
      • 2016-05-24
      • 2011-01-16
      相关资源
      最近更新 更多