2

How can I open the keyboard when a fragment starts? I have already tried this code:

@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;
}

But it doesn't work. I have to open the keyboard at startup.

galath
  • 5,717
  • 10
  • 29
  • 41
Damien
  • 921
  • 4
  • 13
  • 31

3 Answers3

4

For showing keyboard use:

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

For hiding keyboard use:

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

UPDATED
For Fragment:

imgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Aleksandr
  • 4,906
  • 4
  • 32
  • 47
  • 1
    I've already tryed this methods but they only work on activity, not in fragment – Damien Jul 10 '15 at 13:02
  • Somehow, HIDE_IMPLICIT_ONLY was the flag that made it work in my complicated fragment scenario. I don't understand if I read the docs about this flag, though. – Mavamaarten Jan 29 '19 at 10:34
2

Maybe the problem is, that in onCreateView, the view is not on the screen yet.

Try this:

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);
            }
        });
Berťák
  • 7,143
  • 2
  • 29
  • 38
1

Had the same problem, try to use postDelayed

    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager keyboard = (InputMethodManager) mAppContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInput(view, 0);
        }
    }, 100);
Dimanoid
  • 6,999
  • 4
  • 40
  • 55