Search code examples
javaandroidxmlandroid-layoutandroid-custom-view

Check input type of Custom View without getInputType


My question is about Android/Java.

How can I check the input type of an custom view without creating an attr.xml?

My main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        android:ems="10"/>

    <org.javaforum.input
        android:layout_width="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter your E-Mail"
        />

</LinearLayout>

My input.java:

public class input extends TextView{
    public input(Context context, AttributeSet attr) {
        super(context, attr, getIdentifier(attr));
    }
    
    public static int getIdentifier(AttributeSet attr){
        //How can check if input type are textEmailAddress?
    }

    @Override
    public void onFinishInflate() {
        
    }
}

So I wanna know if the inputtype of my custom view was set to "textEmailAddress". How can I do this? I can't use the method getInputType because in my case the object are not initialised yet. How can I solve my problem without the "getInputType" method?


Solution

  • public class Input extends TextView {
    
        private static final int[] INPUT_TYPE_ATTR = new int[]{android.R.attr.inputType};
    
        public Input(Context context, AttributeSet attr) {
            super(context, attr, getIdentifier(context, attr));
        }
    
        public static int getIdentifier(Context context, AttributeSet attr) {
            final TypedArray a = context.obtainStyledAttributes(attr, INPUT_TYPE_ATTR);
            try {
                final int inputType = a.getInt(0, 0);
                if (inputType == (EditorInfo.TYPE_CLASS_TEXT |
                        EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS)) {
                    // your logic here
                }
            } finally {
                a.recycle();
            }
            return 0;
        }
    
        @Override
        public void onFinishInflate() {
            super.onFinishInflate();
        }
    }