I want to focus the first TextInputEditText
in layout and automatically display the soft keyboard when dialog is shown
I'm targeting API level 28.
Layout:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/d_add_edit_name_til"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/activity_vertical_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
android:layout_marginEnd="@dimen/activity_vertical_margin"
android:theme="@style/TextInputLayoutAppearance"
>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/d_add_edit_name_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User email"
android:imeOptions="actionDone"
android:inputType="textCapSentences"
android:singleLine="true"
android:focusableInTouchMode="true"
android:focusable="true"
>
<requestFocus />
</com.google.android.material.textfield.TextInputEditText>
</com.google.android.material.textfield.TextInputLayout>
DialogFragment
code:
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return dialog;
}
....
@Override
public void onResume(){
super.onResume();
int dialogWidth = Functions.convertDpToPixel(300,activity);
int dialogHeight = Functions.convertDpToPixel(250,activity);
new Handler().post(() -> {
getDialog().getWindow().setLayout(dialogWidth, dialogHeight);
});
}
The answers from this thread helped me solve the issue for API < 28.
I know from Android 9 changes documentation that:
Additionally, activities no longer implicitly assign initial focus in touch-mode. Instead, it is up to you to explicitly request initial focus, if desired.
One of the ways to explicitly request initial focus (as discussed here) is by adding <requestFocus />
tag inside EditText
, but still no success for API level 28 + DialogFragment
*Note that DialogFragment
is from andoridx library (androidx.fragment.app.DialogFragment
)
Anyone else having this issue?
Edit:
The only way I managed to make this work is by adding the following code to onViewCreated
:
new Handler().postDelayed(() -> {
nameEt.requestFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(nameEt, InputMethodManager.SHOW_IMPLICIT);
},200);
I don't consider this to be a valid answer as using threads in this manner makes the code unpredictable. Still waiting for a good answer