在片段启动时显示用于EditText的键盘

71
当我的片段开始时,我希望我的EditText获得焦点并让用户可以在其中直接开始输入。我使用requestFocus()方法可以将其设为焦点,但是我无法让键盘弹出。
我已经尝试了以下方法:
edit = (EditText) view.findViewById(R.id.search);
edit.requestFocus();
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);

edit = (EditText) view.findViewById(R.id.search);
InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imgr.showSoftInput(edit, 0);
edit.requestFocus();

如何使EditText出现键盘?


这是对我有效的方法 - https://dev59.com/BmUq5IYBdhLWcg3wJNBA#39658629 - v01d
我的声望太低了,无法对这个问题进行评论。我在这里回答了一个方法来控制何时显示或隐藏键盘(链接:https://dev59.com/543da4cB1Zd3GeqP6u4q#43807917)。 - Catapimba
请查看推荐答案:https://dev59.com/eLnoa4cB1Zd3GeqPXMcU#60666198 - Logo
16个回答

0

简单来说,只需添加两行代码即可完美解决:

如果使用XML

android:focusable="true"
android:focusableInTouchMode="true"

Java中的Else:

view.setFocusableInTouchMode(true);
view.requestFocus();

亲爱的随机访客,请解释一下为什么要点踩。这将有助于我了解这个解决方案的问题所在,因为它对我有效。 - sud007

0

让键盘在片段启动时打开的另一种方法是在onCreateView中调用requestFocus(),并根据情况做出反应,仅当EditText可聚焦时才打开键盘。

if(this.editText.requestFocus())
{
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

0

Kotlin

当你启动片段时,键盘会自动弹出。

    override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val fragmentView = inflater.inflate(R.layout.fragment_main, container, false)

    activity?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    return fragmentView
}

0
toogleSoftInput现已弃用。 对于Kotlin来说。
   private fun showKeyboard() {
    val imm: InputMethodManager =
        context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(binding.yourEditText, 0)
}

-1

就像Nilzor所说的,这个可以工作

imgr.showSoftInput(getView(), InputMethodManager.SHOW_IMPLICIT)

我同意这是比toogleSoftInput更好的解决方案


-1

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