How to show number keyboard on custom view

烈酒焚心 提交于 2019-12-10 13:57:46

问题


I created a custom view:

public class MyCustomView extends LinearLayout {...}

When user touch it, I show keyboard like this:

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

But how can I show a number keyboard, which user can only input digits, just like this for EditText?

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

回答1:


You have to add an override for 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;
    }

    //...
}



回答2:


try to add

 EditText mEditText = new EditText(mContext);
 mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);

and change

imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);

to

imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);

i.e. rewrite your code as

if (show) {
    EditText mEditText = new EditText(mContext);
    mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
    imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);
}

replace mContext is your activity context.



来源:https://stackoverflow.com/questions/28978225/how-to-show-number-keyboard-on-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!