android - 如何在自定义 View 上显示数字键盘

标签 android keyboard android-custom-view

我创建了一个自定义 View :

public class MyCustomView extends LinearLayout {...}

当用户触摸它时,我会像这样显示键盘:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            requestFocus();
            showKeyboard(true);
        }
        return super.onTouchEvent(event);
    }
    public void showKeyboard(boolean show) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (show) {
          imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);
        } else {
          imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }

但是如何显示数字键盘,用户只能输入数字,就像 EditText 一样?

mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
mEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

最佳答案

您必须为 onCreateInputConnection 添加覆盖

public class MyCustomView extends LinearLayout implements View.OnFocusChangeListener {

    //...

    // Make sure to call this from your constructor
    private void initialize(Context context) {
        setFocusableInTouchMode(true);
        setFocusable(true);
        setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (hasFocus) {
            imm.showSoftInput(v, 0);
        } else {
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }

    // Here is where the magic happens
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        outAttrs.inputType = InputType.TYPE_CLASS_NUMBER;
        outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE;
    }

    //...
}

关于android - 如何在自定义 View 上显示数字键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978225/

相关文章:

c - 全局按键监听器

Android:将 CustomView 添加到 OnCreate

android - 如何针对发布版本 APK 运行 Android/Robotium Instrumentation 测试用例?

android - Jetpack 与 RxJava2 和 Realm 组合

c# - WP7 让回车键将文本从文本框发送到文本 block

java - 自定义适配器,选中项背景

java - 将 ArrayList 从 MainActivity 类传递到 Android 中的 CustomView 类

java - JVM/Android 不信任 StartSSL 的根证书

Android listView 找到滚动的像素数量

iphone - 如何在没有键盘的情况下在 UITextView 中获取光标?