【问题标题】:Check input type of Custom View without getInputType检查没有 getInputType 的自定义视图的输入类型
【发布时间】:2021-10-16 15:14:53
【问题描述】:

我的问题是关于 Android/Java。

如何在不创建 attr.xml 的情况下检查自定义视图的输入类型?

我的 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>

我的 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() {
        
    }
}

所以我想知道我的自定义视图的输入类型是否设置为“textEmailAddress”。我怎样才能做到这一点?我不能使用 getInputType 方法,因为在我的情况下,对象尚未初始化。如果没有“getInputType”方法,我该如何解决我的问题?

【问题讨论】:

    标签: java android xml android-layout android-custom-view


    【解决方案1】:
    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();
        }
    }
    

    【讨论】:

    • 什么?!?真的行!!我不明白我必须将 TYPE_CLASS_TEXT 与 TYPE_TEXT_VARIATION_EMAIL_ADDRESS 进行比较。但现在我有作业。我想查找有关它的更多信息。
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    相关资源
    最近更新 更多