我最接近的是:
@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
}
但这并不奏效。在这种情况下,即使没有输入具有焦点,一旦方向更改为肖像,键盘将被拉起。
答案 0 :(得分:0)
使用此util侦听器代码
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;
}
}
}
以下代码用于您的活动
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);
}
答案 1 :(得分: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();
}