The closest I got to is:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
//Some other code
}
But that doesn't work. In this case, even if no input has focus, the keyboard will be pulled up, once the orientation is changed to portrait.
Use this util listener code
import android.app.Activity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
public class KeyboardUtil implements OnGlobalLayoutListener {
static public interface KeyboardListener {
public void onKeyboardVisible(boolean visible);
}
private int mHeight;
private boolean mVisible;
private View mRootView;
private KeyboardListener mListener;
public KeyboardUtil(Activity activity) {
mVisible = false;
mHeight = 0;
if (activity == null) {
return;
}
try {
mRootView = activity.getWindow().getDecorView()
.findViewById(android.R.id.content);
mRootView.getViewTreeObserver().addOnGlobalLayoutListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setListener(KeyboardListener listener) {
this.mListener = listener;
}
@Override
public void onGlobalLayout() {
if (mHeight == 0) {
mHeight = mRootView.getMeasuredHeight();
return;
}
if (mListener == null) {
return;
}
int height = mRootView.getHeight();
if (!mVisible && mHeight > (height + 100)) {
mVisible = true;
mListener.onKeyboardVisible(mVisible);
mHeight = height;
} else if (mVisible && mHeight < (height - 100)) {
mVisible = false;
mListener.onKeyboardVisible(mVisible);
mHeight = height;
}
}
}
Below code use in you activity
new KeyboardUtil(context).setListener(keyboardListener);
KeyboardUtil.KeyboardListener keyboardListener = new KeyboardUtil.KeyboardListener() {
@Override
public void onKeyboardVisible(boolean visible) {
// get configuration here and
if(config is portrait)
hideSoftKeyboard(this); // Provide you activity context
}
};
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
View view = this.getCurrentFocus();
try {
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
} catch (Exception e) {
e.printStackTrace();
}
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.