I'm trying to make a To-Do app. You click on a button which brings up a pop-up where you can enter text and click on add button to have it added to the list. I'd like to have the keyboard show up at appropriate times:
1) When the user clicks on the button, he should be able to enter text without having to click on the edittext field.
2) After the user clicks on add, the keyboard should disappear rather than not going away until the user presses back.
I know this question has been asked before many times but the solutions don't seem to be working for me. Here's the code:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final EditText taskEditText = new EditText(MainActivity.this);
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setNegativeButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
taskEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(taskEditText, InputMethodManager.SHOW_IMPLICIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setPositiveButton("Cancel", null)
.create();
dialog.show();
}
});
updateUI();
}
This question was a bit different earlier and the responses I got didn't work for me.