gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:54:20 27 4
gpt4 key购买 nike

我创建了一个自定义 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com