2012-08-28 32 views
7

¡Soy un principiante autodidacta y aprecio la paciencia! ¡Gracias!OnClickListener dentro de un cuadro de alerta personalizado Android

En Eclipse, hice un diálogo de alerta personalizado con su propio archivo xml ("custom_dialog") y se llama "usernamealert".

Quiero una alerta emergente si el usuario aún no ha ingresado un nombre de usuario (es decir, username.length == 0).

Dentro de este diseño tengo un textView ("¿Cuál es tu nombre?"), EditText y botón ("usernameButton").

Antes de poner en el onclicklistener el botón, todo funcionó. Esta fue mi (relevante) Java:

LayoutInflater inflater = getLayoutInflater(); 
View dialoglayout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)  getCurrentFocus()); 
AlertDialog.Builder usernamebuilder = new AlertDialog.Builder(this); 
usernamebuilder.setView(dialoglayout); 

AlertDialog usernamealert = usernamebuilder.create(); 

Cuando puse el onclicklistener, ¡se rompió! ¿Dónde debería haberlo puesto?

(Lo siguiente es lo que había intentado ... todo en mi OnCreate)

LayoutInflater inflater = getLayoutInflater(); 
View dialoglayout = inflater.inflate(R.layout.custom_dialog, (ViewGroup)getCurrentFocus()); 
AlertDialog.Builder usernamebuilder = new AlertDialog.Builder(this); 
usernamebuilder.setView(dialoglayout); 


Button usernameButton = (Button) usernamealert.findViewById(R.id.usernameButton); 
usernameButton.setOnClickListener(new OnClickListener() { 

@Override 
public void onClick(View v) { 
//store username in sharedprefs 
usernamealert.dismiss(); 



} 
}); 

Después de que el código dije:

if (username.length() == 0) { 
      usernamealert.show(); 
     } 

Una vez más, funcionó antes de empezar a jugar con el ¡¡botón!!

+0

Afte r horas de búsqueda, y finalmente publicando la pregunta, ¡lo descubrí como 2 minutos después! Todo lo que debería haber hecho diferente fue cambiar cómo encontró el botón: Button usernameButton = (Button) usernamealert.findViewById (R.id.usernameButton); debería haber sido: Button usernameButton = (Button) dialoglayout.findViewById (R.id.usernameButton); // dialoglayout es lo que usted llamó la Vista – delfina

+0

¡Bienvenido a StackOverflow! ¿Puedes publicar tu solución como respuesta y aceptarla como la respuesta correcta después de que te permita hacerlo? Eso facilitará que las personas en el futuro encuentren la solución si tienen el mismo problema. – FoamyGuy

+0

su respuesta me ayudó ... aunque por favor haga que su respuesta sea más legible. Voy a agregar mi respuesta debajo de – mcr619619

Respuesta

2

Pruebe esto.

usernamebuilder.setCancelable(false) 
usernamebuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      //do what you want. 
     } 
    }); 

Ver si eso funciona, o si ayuda de alguna manera.

+1

¿Cómo descarto este diálogo cuando agrego un onClickListener personalizado en un ImageView? – 4ndro1d

+0

@ 4ndro1d Use "dialog.dismiss();" dentro del método onClick que está dentro del setOnClickListener(); – AJW

7

se necesita para especificar dónde será la búsqueda de código en el botón, si su único "findViewById" sería buscar en el xml del huésped, debe ser

LayoutInflater inflater =getLayoutInflater(); 
       View myview = inflater.inflate(R.layout.dialoghireteachernegotiate, null); 
       // Inflate and set the layout for the dialog 
       // Pass null as the parent view because its going in the dialog layout 
       builder.setView(myview); 
       Button addS = (Button) myview.findViewById (R.id.bAddS); 

Esto es parte de mi clase, Hireteachernegotiate.class, que tiene un diseño de hireteachernegotiate.xml

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       // Get the layout inflater 
       LayoutInflater inflater =getLayoutInflater(); 
       View myview = inflater.inflate(R.layout.dialoghireteachernegotiate, null); 
       // Inflate and set the layout for the dialog 
       // Pass null as the parent view because its going in the dialog layout 
       builder.setView(myview); 

       Button addS = (Button) myview.findViewById (R.id.bAddS); 
       addS.setOnClickListener(new View.OnClickListener() { 

        public void onClick(View v) { 
         //do some stuff 
        } 
       }); 

       Button minusS = (Button) myview.findViewById (R.id.bMinusS); 
       addS.setOnClickListener(new View.OnClickListener() { 

        public void onClick(View v) { 
         //do other stuff 
        } 
       }); 

       // Add action buttons 
         builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 


           dialog.cancel(); 
          } 
         }); 
        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
         } 
        }); 



      builder.show(); 

Ésta es la disposición de diálogo

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

    <Button 
     android:id="@+id/bAddS" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 


    <Button 
     android:id="@+id/bMinusS" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 

</LinearLayout> 
+0

el nombre del diseño del diálogo es "dialoghireteachernegotiate.xml" – mcr619619

Cuestiones relacionadas