Robb1 Robb1 - 1 month ago 10
Android Question

How to force a single line input in an Alert Dialog?

I have this AlertDialog showing up when the user presses the floating button. I don't want the user to be able to insert a multiple line input (i.e. ignoring her if she tries to press the enter key). How do I do this? Here's my code:

final EditText input = new EditText(getActivity());
new AlertDialog.Builder(getActivity()).setTitle("Package creation").setMessage("Insert package name:").setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
CharSequence toastText;
if (input.length() > 0) {
/* save the package name in the database */
toastText = getString(R.string.toast_package_saved);
} else toastText = getString(R.string.toast_empty_text);
Toast toast = Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT);
toast.show();
input.getText().clear();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// do nothing
}
}).show();

Answer

In Xml

Put android:maxLines="1" in the EditText from the input xml layout.

Also choose an InputType, as Frédéric Letellier mentionated in his answer.

For example, android:inputType="phone"

More info in Specifying the Input Method Type

In Java

input.setMaxLines(1);
input.setInputType(InputType.TYPE_CLASS_PHONE);

In these examples, it is showed a setting for phone number. You can view the other types in InputType


ps: Also in xml, you can use android:singleLine="true", but this parameter is deprecated. So the first option sounds better.