I want to make the keyboard open automatically when the fragment starts. Now my code looks like this:
class NewPostFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentNewPostBinding.inflate(inflater, container, false)
binding.editText.requestFocus()
AndroidUtils.showKeyboard(binding.editText)
binding.OK.setOnClickListener {
AndroidUtils.hideKeyboard(requireView())
findNavController().navigateUp()
}
return binding.root
}
}
AndroidManifest.xml file:
<activity
android:name=".activity.AppActivity"
android:exported="true"
android:windowSoftInputMode="stateVisible|adjustResize">
<nav-graph android:value="@navigation/nav_main" />
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And AndroidUtils file:
object AndroidUtils {
fun hideKeyboard(view: View) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}
The problem is that the keyboard does not open, but the focus in the editText field is displayed.
Calling the binding.editText.callOnClick()
method does not give any result.
I also tried this code on showKeybord function:
fun showKeyboard(view: View) {
if (view.requestFocus()) {
val imm =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
}
But keybord is opens only after the first start fragment and method toggleSoftInput()
is marked is deprecated. And it does not opens for the second and next times. It is run again only after the application is hard closed.
When I did the same thing in the activity (not in the fragment), the keyboard opened after calling the requestFocus()
function.
I have read the documentation on https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility and I have read other similar questions on the stackoverflow, but I still don't get the expected result.
What could be the problem?
How do I get the keyboard to open automatically when the fragment start?