Same snippets, edittext and requestfocus

Sorry to ask you again for help on this, but all the other posts did not help.

Here's the scenario: I have Acivity ('A'), which includes a layout with a fragment inside. This fragment is replaced with user input. One of these snippets has an edittext inside, which I want to focus on creating and showing a damn soft keyboard. So, in the onCreateView () fragment I use:

mEt = (EditText) v.findViewById(R.id.et); mEt.setImeOptions(EditorInfo.IME_ACTION_DONE); mEt.requestFocus(); 

So, it works for the first time, but if a fragment is replaced and re-created later, it gets focus, but the keyboard does not appear.

I tried to hide the keyboard before the fragment was destroyed with:

 InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.hideSoftInputFromWindow(et.getWindowToken(), 0); 

or to explicitly display the keyboard using:

 InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.showSoftInput(et, 0); 

but (as you can imagine from what I'm posting here :)), the problem remains.

I also desperately thought about the activity / fragment problem and used the same methods as the listeners in action, with no luck.

Pretty upset, please help :)

+6
source share
1 answer

I just solved this problem. We had an activity that swapped several fragments with text fields that needed focus and a keyboard.

There are two ways to solve this, both of which I played. This is the method I finally went with.

 @Override private View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ... if (savedInstanceState != null && !savedInstanceState.isEmpty()){ msDialogMessage = savedInstanceState.getString(STATE_DAILOG_MSG); } else{ Utils.setKeyboardFocus(mEditTextUserName); } ... } /** * Used to set focus and show keyboard (if needed) for a specified text field * @author Ty Smith * @param primaryTextField */ public static void setKeyboardFocus(final EditText primaryTextField) { (new Handler()).postDelayed(new Runnable() { public void run() { primaryTextField.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0)); primaryTextField.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0)); } }, 100); } 

Although if your fragments do not play well and the life cycle methods do not call correctly, you can consider my other way.

I will not send the code, but just put the focus capture method in the user listener and call it from the action when you put the fragment in the foreground.

+14
source

Source: https://habr.com/ru/post/902572/


All Articles