Search code examples
androidandroid-edittextandroid-dialogfragmentandroid-keypaddialogfragment

EditText in DialogFragment: How to limit to single line and show "Search" icon at the keyboard?


I have prepared a simple test project at GitHub for my question:

screenshot

In a word game for Android I would like to offer the user a possibility to check, if a word is available in the game dictionary - by displaying a DialogFragment with a single EditText.

Here is a code excerpt from the custom FindWordDialogFragment.java:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final EditText editText = new EditText(getContext());
    editText.setMaxLines(1);
    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        public boolean onEditorAction(TextView v,
                                      int actionId,
                                      KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                String word = editText.getText().toString();
                mListener.findWord(word);
                dismiss();
                return true;
            }
            return false;
        }
    });

    return new AlertDialog.Builder(getContext())
        .setIcon(R.mipmap.ic_launcher)
        .setTitle(R.string.find_word_title)
        .setView(editText, 16, 16, 16, 16)
        .setPositiveButton(R.string.find_word_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String word = editText.getText().toString();
                    mListener.findWord(word);
                }
            }
        )
        .setNegativeButton(R.string.find_word_cancel, null)
        .create();
}

Unfortunately, there are 2 problems (marked by red arrows in the above screenshot):

  1. There are still several lines of text in the EditText
  2. And there is no "Search" icon displayed at the keyboard

Can anybody please help here?


Solution

  • I tend to find setSingleLine(true) works more consistently than setMaxLines(1).

    For search, try adding editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH). Your code handles the search event when it receives one, but that doesn't tell it to send it in the first place.