7

How do I get the attribute value "required" in my Activity Class?

1. values\attrs.xml

<declare-styleable name="EditText"> 
    <attr name="required" format="boolean" />
</declare-styleable> 

2. layout\text.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom="http://schemas.android.com/apk/res/com.mycompany.test"
    android:baselineAligned="false"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txtTest"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:inputType="text" 
        custom:required="true" />

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
mwramos
  • 71
  • 1
  • 2

1 Answers1

2

In EditText constructor add logic to read data from xml:

    public EditText(final Context context, final AttributeSet attrs, final int defStyle) 
    {
      super(context, attrs, defStyle);
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditText);

      final int N = a.getIndexCount();
      for (int i = 0; i < N; ++i)
      {
        int attr = a.getIndex(i);
        switch (attr)
        {
            case R.styleable.EditText_required: {
                if (context.isRestricted()) {
                    throw new IllegalStateException("The "+getClass().getCanonicalName()+":required attribute cannot "
                            + "be used within a restricted context");
                }

                boolean defaultValue = false;
                final boolean required = a.getBoolean(attr, defaultValue );
                //DO SOMETHING
                break;
            }
            default: 
                break;
        }
      }
      a.recycle();
    }

The switch construct was used to check for many custom attributes. If you are only interested in one attribute you can skip switch statement

If you want to learn more, especially how to add method handler using xml attribute read this: Long press definition at XML layout, like android:onClick does

ffonz
  • 1,304
  • 1
  • 11
  • 29
Aleksander Gralak
  • 1,509
  • 10
  • 26