InputMethodManager.showSoftInput 为什么或何时返回 false?

Hau*_*Luu 5 android android-softkeyboard

我试图在屏幕上弹出一个软键盘,首先以编程方式加载(不更改清单中的 windowSoftInputMode)。

有趣的是在屏幕上第一次加载,它根本不起作用。这是代码块。

mEDT.requestFocus();
mEDT.requestFocusFromTouch();
mImm.showSoftInput(mEDT, InputMethodManager.SHOW_IMPLICIT);
Run Code Online (Sandbox Code Playgroud)

showSoftInput 返回 false,这导致软键盘没有显示。

但是当我点击 EditText 时。showSoftInput 返回 true 并显示软键盘。

谁能向我解释发生了什么?

Ben*_*Ben 8

你在使用碎片吗?我发现showSoftInput()Fragments 不可靠。

检查源代码后,我发现调用requestFocus()/ onCreate()oronCreateView()onResume()不会立即使对象获得焦点。这很可能是因为内容视图尚未创建。因此焦点发生在 Activity 或 Fragment 初始化期间的某个时间。

showSoftInput()我打电话的成功率要高得多onViewCreated()

public class MyFragment extends Fragment {
    private InputMethodManager inputMethodManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout, container, false);

        EditText text1 = (EditText) view.findViewById(R.id.text1);
        text1.requestFocus();

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view.findFocus(), InputMethodManager.SHOW_IMPLICIT);
        super.onViewCreated(view, savedInstanceState);
    }
}
Run Code Online (Sandbox Code Playgroud)

即使您不使用 Fragments,我敢打赌同样的规则也适用。因此,请确保在调用 showSoftInput() 之前创建视图。