这是从任何地方隐藏键盘的解决方案。
首先在您选择的活动中创建状态侦听器和将执行关闭的方法(基于打开状态)。
public class MainActivity extends SherlockFragmentActivity {
private boolean mKeyboardOpen = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// add "keyboard open listener"
final View v = findViewById(R.id.pager);
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int hRoot = v.getRootView().getHeight();
int hView = v.getHeight();
int heightDiff = hRoot - hView;
// if more than 150 pixels, its probably a keyboard...
mKeyboardOpen = heightDiff > 150;
Log.d(TAG, "hRoot=" + hRoot + ", hView=" + hView + ", mKeyboardOpen=" + mKeyboardOpen);
}
});
}
public void closeSoftKeyboard() {
if (mKeyboardOpen) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
}
来自任何地方的第二个电话((MainActivity) getActivity()).closeSoftKeyboard();
,例如您的 EditText 的OnClickListener()
.
提示:我正在使用 ViewPager 根视图 (R.id.pager),但您可能应该将其替换为您的视图根 id。