Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Created April 16, 2020 02:50
Show Gist options
  • Save brownsoo/08709f136fad3fed1f849921b70c4cf3 to your computer and use it in GitHub Desktop.
Save brownsoo/08709f136fad3fed1f849921b70c4cf3 to your computer and use it in GitHub Desktop.
Making a input password dialog programmatically
// activity with android:windowSoftInputMode="stateHidden"
private fun showPasswordDialog() {
val context = this.context ?: return
val editText = EditText(context)
editText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
editText.filters = arrayOf(InputFilter.LengthFilter(4))
val frame = FrameLayout(context)
frame.addView(editText)
val param = FrameLayout.LayoutParams(-1, -2)
param.marginStart = UiUtil.dp2px(16f)
param.marginEnd = UiUtil.dp2px(16f)
editText.layoutParams = param
val dialog = MaterialAlertDialogBuilder(context)
.setView(frame)
.setTitle(R.string.open_content)
.setMessage(R.string.use_password_for_content)
.setPositiveButton(R.string.confirm) { _, _ ->
getMainHandler()?.post { handleInputPassword(editText.text.toString()) }
}
.setNegativeButton(R.string.cancel) { _, _ ->
}
.setNeutralButton(R.string.reset_password) { _, _ ->
showResetPasswordDialog()
}
.create()
dialog.setOnShowListener {
editText.requestFocus()
getMainHandler()?.postDelayed({
UiUtil.showKeyboard(context, editText)
}, 100)
}
dialog.setOnDismissListener {
getMainHandler()?.postDelayed({
hideKeyboard()
editText.clearFocus()
}, 100)
}
editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
val typed = editText.text.toString()
getMainHandler()?.post { handleInputPassword(typed) }
dialog.dismiss()
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
dialog.show()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment