How to read custom attributes in Android

2019-01-26 13:18发布

问题:

I can create custom attributes and apply them to regular EditTexts, like this:

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

My question: can I read the value of those custom attributes without creating a class that extends EditText? I mean, I want to read custom attributes from my Activity, but the examples I see so far requires me to read the values from the constructor of a custom view, like here: Defining custom attrs

回答1:

My question: can I read the value of those custom attributes without creating a class that extends EditText?

Yes, you can get those attributes without extending the classes. For this you could use a special Factory set on the LayoutInflater that the Activity will use to parse the layout files. Something like this:

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

where the CustomAttrFactory is like this:

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;
    }
}

The idea comes from a blog post, you may want to read it for additional information.

Also, depending on that custom attribute(or attributes if you have other) you could just use android:tag="whatever" to pass the additional data(and later retrieve it in the Activity with view.getTag()).

I would advise you to not use those custom attributes and rethink your current approach.



回答2:

I'd say no, you can't. I checked sources of EditText and it parents and didn't found place where it stores custom atributes to instance property so you can use them later. So I think you need to create your own class that extends EditText.