2010-04-05 18 views
6

Estoy tratando de agregar algo de validación de texto a un campo de texto de edición ubicado dentro de un cuadro de diálogo de alerta. Indica al usuario que ingrese un nombre.Validación nula en el cuadro Editar texto en el Diálogo de alerta - Android

Quiero agregar algo de validación para que, si lo que han ingresado es en blanco o nulo, no haga nada aparte de crear un error diciendo Toast.

hasta ahora tengo:

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    alert.setTitle("Record New Track"); 
    alert.setMessage("Please Name Your Track:"); 
    // Set an EditText view to get user input 
    final EditText trackName = new EditText(this); 
    alert.setView(trackName); 
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int whichButton) { 

      String textString = trackName.getText().toString(); // Converts the value of getText to a string. 
      if (textString != null && textString.trim().length() ==0) 
      { 

       Context context = getApplicationContext(); 
       CharSequence error = "Please enter a track name" + textString; 
       int duration = Toast.LENGTH_LONG; 

       Toast toast = Toast.makeText(context, error, duration); 
       toast.show(); 


      } 
      else 
      { 

       SQLiteDatabase db = waypoints.getWritableDatabase(); 
       ContentValues trackvalues = new ContentValues(); 
       trackvalues.put(TRACK_NAME, textString); 
       trackvalues.put(TRACK_START_TIME,tracktimeidentifier); 
       insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues); 

      } 

Pero esto sólo cierra el diálogo de alerta y muestra el pan tostado. Quiero que el cuadro de diálogo de alerta aún esté en la pantalla.

Gracias

Respuesta

3

Creo que debería volver a crear el Dialog, ya que parece que el DialogInterface dada como parámetro en onClick() no le da una opción para detener el cierre de la Dialog.

también tengo un par de consejos para usted:

Intente utilizar Activity.onCreateDialog(), Activity.onPrepareDialog() y por supuesto Activity.showDialog(). Hacen que el uso del diálogo sea mucho más fácil (al menos para mí), también el uso del diálogo se parece más al uso del menú. Usando estos métodos, también podrá mostrar el cuadro de diálogo más fácilmente.

Quiero darle un consejo. No es una respuesta a su pregunta, pero hacer esto en una respuesta es mucho más legible.

En lugar de mantener una referencia a un objeto AlertDialog.Builder(), sólo tiene que hacer:

new AlertDialog.Builder(this) 
.setTitle("Record New Track") 
.setMessage("Please Name Your Track:") 
//and some more method calls 
.create(); 
//or .show(); 

le ahorra una referencia y un montón de escribir;). (¿casi?) Todos los métodos de AlertDialog.Builder devuelven un objeto AlertDialog.Builder, que puede invocar directamente a un método.

Lo mismo ocurre con Toast s:

Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show(); 
1

Lo que debe hacer es crear un diseño de XML personalizado que incluye un cuadro de texto y un botón Aceptar en lugar de utilizar .setPositiveButton. Luego puede agregar un oyente de clic a su botón para validar los datos y descartar el diálogo.

que debe ser usado en CreateDialog:

protected Dialog onCreateDialog(int id) 
{ 
      LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

if (id==EDIT_DIALOG) 
{ 
      final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit)); 

      final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack); 
      final EditText name=(EditText) layout.findViewById(R.id.EditText_Name); 
      okButton.setOnClickListener(new View.OnClickListener() 
      { 
       public void onClick(View v) { 
        String textString = trackName.getText().toString(); 
        if (textString != null && textString.trim().length() ==0) 
        { 
         Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show(); 
        } else 
         removeDialog(DIALOG_EDITTRACK); 
       } 
      });    
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      builder.setView(layout); 
      builder.setTitle("Edit text"); 

      AlertDialog submitDialog = builder.create();    
      return submitDialog; 
} 
3

hago un nuevo método dentro de mi clase que muestra la alerta y poner todo el código para crear la alerta de que un método. luego, después de llamar a Toast, llamo a ese método. Supongamos que denominé ese método createAlert(), luego tengo,

createAlert(){ 

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
alert.setTitle("Record New Track"); 
alert.setMessage("Please Name Your Track:"); 
// Set an EditText view to get user input 
final EditText trackName = new EditText(this); 
alert.setView(trackName); 
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 

     String textString = trackName.getText().toString(); // Converts the value of getText to a string. 
     if (textString != null && textString.trim().length() ==0) 
     { 

      Context context = getApplicationContext(); 
      CharSequence error = "Please enter a track name" + textString; 
      int duration = Toast.LENGTH_LONG; 

      Toast toast = Toast.makeText(context, error, duration); 
      toast.show(); 
      createAlert(); 



     } 
     else 
     { 

      SQLiteDatabase db = waypoints.getWritableDatabase(); 
      ContentValues trackvalues = new ContentValues(); 
      trackvalues.put(TRACK_NAME, textString); 
      trackvalues.put(TRACK_START_TIME,tracktimeidentifier); 
      insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues); 

     } 
} 
0

Utilice este código para mostrar el cuadro de diálogo.

public void onClick(DialogInterface dialog, int whichButton) { 

      String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string. 
      if (textString != null && textString.trim().length() ==0) 
      {  
       Context context = getApplicationContext(); 
       CharSequence error = "Please enter a track name" + textString; 
       int duration = Toast.LENGTH_LONG; 

       Toast toast = Toast.makeText(context, error, duration); 
       toast.show(); 

       new AlertDialog.Builder(this) 
       .setTitle("Message") 
       .setMessage("please enter valid field") 
       .setPositiveButton("OK", null).show();    
      } 

Esto creará un diálogo para que, editText está vacía o cuáles son las condiciones que quiere.

0

// si la vista no se crea una instancia, siempre devuelve nulo para los valores de texto de edición.

View v = inflater.inflate(R.layout.new_location_dialog, null); 
builder.setView(v); 



final EditText titleBox = (EditText)v.findViewById(R.id.title); 
final EditText descriptionBox = (EditText)v.findViewById(R.id.description); 
Cuestiones relacionadas