Skip to content

Instantly share code, notes, and snippets.

@AlexMisiulia
Created June 9, 2019 17:48
Show Gist options
  • Save AlexMisiulia/73c6266956f1781d5612c8cea2c51c51 to your computer and use it in GitHub Desktop.
Save AlexMisiulia/73c6266956f1781d5612c8cea2c51c51 to your computer and use it in GitHub Desktop.
A code block which shows how to show Android keyboard after user press back button when current Activity has focus.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button: Button = findViewById(R.id.button)
button.setOnClickListener {
startActivity(Intent(this, DetailsActivity::class.java))
}
}
override fun onStart() {
super.onStart()
// show the keyboard if has focus
currentFocus?.let {
showSoftKeyboard(it)
}
}
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
// here is one more tricky issue
// imm.showSoftInputMethod doesn't work well
// and imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0) doesn't work well for all cases too
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment