8

我可以创建自定义属性并将它们应用于常规EditTexts,如下所示:

<EditText
     android:id="@+id/field1"
     custom:attr1="whatever"
     (...)
<EditText
     android:id="@+id/field2"
     custom:attr1="whatever2"
     (...)

我的问题:我可以在不创建扩展类的情况下读取这些自定义属性的值EditText吗?我的意思是,我想从我Activity.

4

2 回答 2

8

我的问题:我可以在不创建扩展 EditText 的类的情况下读取这些自定义属性的值吗?

是的,您可以在不扩展类的情况下获得这些属性。为此,您可以使用一个特殊的Factory集合LayoutInflaterActivity解析布局文件。像这样的东西:

super.onCreate(savedInstanceState);
getLayoutInflater().setFactory(new CustomAttrFactory());
setContentView(R.layout.the_layout);

CustomAttrFactory这样的:

public static class CustomAttrFactory implements Factory {

    @Override
    public View onCreateView(String name, Context context,
            AttributeSet attrs) {
        String attributeValue = attrs
                .getAttributeValue(
                        "http://schemas.android.com/apk/res/com.luksprog.droidproj1",
                        "attrnew");
        Log.e("ZXX", "" + attributeValue);
        // if attributeValue is non null then you know the attribute is
        // present on this view(you can use the name to identify the view,
        // or its id attribute)
        return null;
    }
}

这个想法来自博客文章,您可能需要阅读它以获取更多信息。

此外,根据该自定义属性(或其他属性),您可以只使用它android:tag="whatever"来传递其他数据(然后在Activitywith中检索它view.getTag())。

我建议您不要使用那些自定义属性并重新考虑您当前的方法。

于 2013-01-15T16:03:23.107 回答
0

我会说不,你不能。我检查了它的来源EditText和它的父母,但没有找到它将自定义属性存储到实例属性的位置,以便您以后可以使用它们。所以我认为你需要创建自己的扩展类EditText

于 2013-01-15T14:06:07.610 回答