【发布时间】:2015-09-28 23:57:48
【问题描述】:
问题:
我想在按下“添加”按钮时隐藏键盘。屏幕上有两个
EditText。键盘在启动 Activity 时不会出现,这很好,但在单击按钮时它不会消失。
以下是我看到的 Stack Overflow 中所有可能的问题,但它们的答案对我没有帮助:
Close/hide the Android Soft Keyboard
Programmatically Hide/Show Android Soft Keyboard
How to hide Soft Keyboard when activity starts
How to hide soft keyboard on android after clicking outside EditText?
还有很多其他的。
这是我的代码:
添加活动
public class AddActivity extends ActionBarActivity {
EditText text1,text2;
DbHelper db;
ListView l;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
db = new DbHelper(this);
l = (ListView) findViewById(R.id.listInAddActivity);
text1 = (EditText) findViewById(R.id.i1);
text2 = (EditText) findViewById(R.id.i2);
// text1.setInputType(InputType.TYPE_NULL);
// text2.setInputType(InputType.TYPE_NULL);
hideKeyboard();
loadDataInAdd();
}
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1,s2);
loadDataInAdd();
hideKeyboard();
}
public void loadDataInAdd()
{
try {
Cursor cursor = db.fetchData();
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.tasks,
cursor,
new String[]{db._ID, db.COLUMN_1, db.COLUMN_2},
new int[]{R.id.idnum, R.id.c1, R.id.c2}, 0);
l.setAdapter(myAdapter);
}
catch(NullPointerException e)
{
e.printStackTrace();
}
// MainActivity.loadData();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
大多数答案都是关于InputManager 方法,但它对我不起作用,即单击按钮时不会隐藏键盘。这是我使用的InputManager 的另一种变体:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
我也试过这个:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
这也不起作用(点击按钮时键盘不会隐藏)。
我也试过了:
<activity android:name=".AddActivity"
android:label="@string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
和
<activity android:name=".AddActivity"
android:label="@string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
有了这个,我的应用程序停止了工作:
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
这个完全隐藏了键盘(即使点击了editText,键盘也没有出现):
text1.setInputType(InputType.TYPE_NULL);
text2.setInputType(InputType.TYPE_NULL);
【问题讨论】: