安卓:在EditText中显示键盘

4

我在编写 Android 应用程序时遇到了一个非常简单的问题。我有一系列每行一个的 EditText 对象。

当用户长按 EditText 时,我需要显示键盘。用户进行长按操作时,我将调用此方法:

private void setNameAsEditable(View rowView, boolean setToEditable) {

    EditText textView = (EditText) rowView
        .findViewById(R.id.edittext_name);
    textView.setFocusableInTouchMode(setToEditable);
    textView.setFocusable(setToEditable);
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);
}

编辑文本框变为可编辑状态(可以看到下划线和光标,如下图所示)

enter image description here

但键盘没有弹出。

我尝试了来自stackoverflow的各种解决方案(例如这个),但都无效。

我甚至尝试了

this.getWindow().setSoftInputMode ( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

我希望当用户长按 EditText 时,软键盘能够立即弹出。请问有人可以帮忙吗?


在那个链接中,他尝试了不同的AVD并且代码运行良好。你试过吗? - Kanwaljit Singh
1
还可以尝试在InputMethodManager上方添加textView.requestFocus();。因为除了您的代码,我只有这一行,并且似乎运行良好。 - Hariharan
非常感谢@Tamilan!你的回答和Amit的回答一起帮了我! - user2903200
4个回答

3

你可以尝试一下,对我来说它运行良好。

 et =(EditText) findViewById(R.id.edittext_name);
      imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
      et.setText("hide key board");
      et.setFocusable(false);
     et.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            et.setFocusableInTouchMode(true);
            imm.showSoftInput(et, 0);
            et.setText("show key board long pressed");
            return false;
        }
    });

非常感谢@Amit!这个和Tamilan的回答一起帮了我。 - user2903200

3
这是最终起作用的内容(Amit和Tamilan的答案),非常感谢!
private void setNameAsEditable (View rowView, boolean setToEditable) {

    EditText textView = (EditText) rowView
            .findViewById(R.id.edittext_name);
    textView.setFocusableInTouchMode(setToEditable);
    textView.setFocusable(setToEditable);

    InputMethodManager imm = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);

    if (setToEditable) {
         textView.requestFocus();
        imm.showSoftInput(textView, 0);
    }
}

1
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

0

请检查您的XML布局中是否有android:focusable="false"或android:focusableInTouchMode="false"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接