代码正在运行并打印出“解除键盘”,但键盘不会消失。视图v只是背景视图,按钮和文本字段位于相对布局的顶部。我正在运行S3 API 18
public View v;
public EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.v = (View) findViewById(R.id.backgroundView);
this.et = (EditText) findViewById(R.id.searchBox);
Button testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println("dismissing keyboard");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(getWindow().getCurrentFocus().getWindowToken() ,0);
}
});
this.v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("dismissing keyboard");
//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromInputMethod(getWindow().getCurrentFocus().getWindowToken() ,0);
}
});
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<View
android:id="@+id/backgroundView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<EditText
android:id="@+id/searchBox"
android:layout_width="fill_parent"
android:layout_height= "wrap_content"
android:layout_centerVertical="true"
/>
<Button
android:id="@+id/searchButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/searchBox"
android:text="Search"
/>
<Button
android:id="@+id/testButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/searchBox"
android:text="testButton"
/>
答案 0 :(得分:1)
您传递的视图应该是edittext。
public static void hideKeyboard(Context context, View layoutThatContainsEditText) {
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(layoutThatContainsEditText.getApplicationWindowToken(), 0);
}
答案 1 :(得分:0)
变化
getWindow().getCurrentFocus().getWindowToken()
到
et.getApplicationWindowToken()