如何在自定义视图上显示数字键盘

时间:2015-03-11 03:45:46

标签: android keyboard android-custom-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);

2 个答案:

答案 0 :(得分:3)

您必须为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;
    }

    //...
}

答案 1 :(得分:0)

尝试添加

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

并更改

imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);

imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);

即。将代码重写为

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

替换mContext是您的活动背景。