Vanquiza Vanquiza - 3 months ago 15
Android Question

How do I set a placeholder on Edittext in Android and use it if no input has been typed by user?

I would like to have an EditText in android where I have a placeholder, which will be used AS my input if the user types nothing. The edit text is used in a prompt in my case.

I am aware of "hint" excisting, which is a placeholder, but it doesn't use it as an input. If I have hint set to "AAA" and the user types nothing and presses "OK" I will get an empty string, not "AAA".

Here's my code:

private void promptForUsername(){
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);

View promptView = layoutInflater.inflate(R.layout.prompts, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);

final EditText input = (EditText) promptView.findViewById(R.id.userInput);


//setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
addEvent(levelSelected, input.getText().toString(), Integer.parseInt(points), time + "s");
sqlLogic();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sqlLogic();
dialog.cancel();
}

});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();

input.setFocusableInTouchMode(true);
input.requestFocusFromTouch();

InputMethodManager lManager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
lManager.showSoftInput(input, 0);

}




version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type username:"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/userInput"
android:layout_width="match_parent"
android:inputType="text"
android:layout_height="wrap_content"
android:maxLength="13"
android:hint="AAA">

<requestFocus />
</EditText>
</LinearLayout>

Answer

Add this static method somewhere:

static CharSequence getTextOrHint(TextView tv) {
  return(TextUtils.isEmpty(getText()) ? getHint() : getText());
}

Then use that method to retrieve your value, which will return the text if it exists, or the hint if it does not.