I am currently trying to keep an alert dialog with edit text showing on the screen. As usual there are Okay and Cancel buttons and I wanted to add a little error handling to the process. If the user does not enter any text in the edit text box and tries to press okay, I want a toast message to pop up notifying them of their error. The dialog box should still be kept showing because they still need to enter something if they want to press okay.
This is what I have so far. BTW, the dialog box pops up based on what the user selected from a drop down list. Any help in getting the dialog box to stay up would be greatly appreciated!!!
Here is my code:
regionSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> parent, View v, int position, long rowId)
{
regionSelect = regionSpinner.getItemAtPosition(position).toString();
regionInteger = (int) regionSpinner.getItemIdAtPosition(position);
chosenRegion = regionSpinner.getSelectedItem().toString();
if (chosenRegion.equals(ENTER_OPTION))
{
final AlertDialog.Builder alert = new AlertDialog.Builder(LoginActivity.this);
alert.setTitle(TITLE_DIALOG);
// Set an EditText view to get user input
final EditText input = new EditText(LoginActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
if(input.getText().toString().length() > 0 && input != null)
{
textValueForEnteredRegion = input.getText().toString();
Toast.makeText(getApplicationContext(), "Input Accepted", Toast.LENGTH_SHORT).show();
dialog.dismiss();
//added soft keyboard code to make keyboard go away.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
else
{
Toast.makeText(getApplicationContext(), "You must enter a selection.", Toast.LENGTH_SHORT).show();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
// Canceled.
dialog.dismiss();
//added soft keyboard code to make keyboard go away.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
alert.show();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
Override the button’s onClick methods.
See: Android SDK override AlertDialog events
Edit: Looks like you already have this… you just need to get rid of dialog.dismiss() in your onPostitiveButton onClick method, and put a conditional around it that checks to see if your EditText has some text in it.