I know, it's asked many times, but for old Android versions and not all solutions working.
I need to programmatically control onscreen keyboard on Android 10 system:
Code can be in kotlin/java.
Add these two properties to your parent layout (ex: Linear Layout, Relative Layout)
android:focusable="false"
android:focusableInTouchMode="false"
in your activity:
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Alternatively,
you could also declare in your manifest file's activity
<application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name" android:windowSoftInputMode="stateHidden" >
If you have already been using android:windowSoftInputMode for a value like adjustResize or adjustPan, you can combine two values:
<activity... android:windowSoftInputMode="stateHidden|adjustPan"... >
show keyboard programmatically:
public static boolean showKeyboard(View view) {
if (view == null) {
return false;
}
try {
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
view.requestFocus();
return inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
} catch (Exception ignored) {
}
return false;
}
hide keyboard:
public static void hideKeyboard(View view) {
if (view == null) {
return;
}
try {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (!imm.isActive()) {
return;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
view.clearFocus();
} catch (Exception e) {
}
}
on keyboard show listener:
public static void OnkeyBoardShowListener(final Activity activity) {
final View activityRootView = activity.findViewById(android.R.id.content);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
activityRootView.getWindowVisibleDisplayFrame(rect);
int heightRoot = activityRootView.getRootView().getHeight();
int heightDiff = heightRoot - rect.bottom;
if (heightDiff > dpToPx(activity, 200)) {
//Keyboard is open
}else if (heightDiff < dpToPx(activity, 200)) {
//Keyboard is close
}
}
});
}
convert Dp to Px:
private static float dpToPx(Context context, int dp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp, metrics);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.