【问题标题】:How to open keyboard in a fragment如何在片段中打开键盘
【发布时间】:2015-07-10 12:36:27
【问题描述】:

片段启动时如何打开键盘?我已经尝试过这段代码:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view =inflater.inflate(R.layout.mylayout,container,false);
    TextView TVLarghezza = (TextView) view.findViewById(R.id.larghezza);
    TVLarghezza.requestFocus();
    InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imgr.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    return view;
}

但它不起作用。我必须在启动时打开键盘。

【问题讨论】:

标签: android android-fragments keyboard


【解决方案1】:

用于显示键盘使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

用于隐藏键盘:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 

更新
对于片段:

imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

【讨论】:

  • 我已经尝试过这种方法,但它们只适用于活动,而不是片段
  • 不知何故,HIDE_IMPLICIT_ONLY 是让它在我复杂的片段场景中工作的标志。不过,我不明白我是否阅读过有关此标志的文档。
【解决方案2】:

也许问题是,在 onCreateView 中,视图还没有出现在屏幕上。

试试这个:

final TextView TVLarghezza = (TextView) view.findViewById(R.id.larghezza);
TVLarghezza.post(new Runnable() {
        @Override
        public void run() {
            TVLarghezza.requestFocus();
            InputMethodManager imgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imgr.showSoftInput(TVLarghezza, InputMethodManager.SHOW_IMPLICIT);
            }
        });

【讨论】:

    【解决方案3】:

    遇到同样的问题,试试postDelayed

        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager keyboard = (InputMethodManager) mAppContext
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.showSoftInput(view, 0);
            }
        }, 100);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      相关资源
      最近更新 更多