2017-10-07 2 views
-2

Ich bin neu in Android Entwicklungsbereich, so für eine AlertDialog Box versucht und ich Probleme damit. Hier ist mein Abschnitt Code für AlertDialog.mein Alarmdialog funktioniert nicht?

public void teacherLogin(View view) 
{ 

    AlertDialog.Builder alert = new 
    AlertDialog.Builder(getApplicationContext()); 
    alert.setTitle("Login"); 
    alert.setPositiveButton("Login", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialogInterface, int i) { 

      Toast.makeText(getApplicationContext(), "you clicked login", 
      Toast.LENGTH_SHORT).show(); 

     } 
    }); 
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
    { 
     @Override 
     public void onClick(DialogInterface dialogInterface, int i) { 
      Toast.makeText(getApplicationContext(), "Cancelled", 
      Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    AlertDialog dialog = alert.create(); 
    dialog.setCancelable(false); 
    dialog.setCanceledOnTouchOutside(false); 
    dialog.show(); 
} 

Und hier ist mein xml-Code für Button die teacherLogin aufgerufen() -Methode

<Button 
    android:id="@+id/teacher_loginbtn" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="28dp" 
    android:onClick="teacherLogin" 
    android:text="Teacher's Login" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" 
    android:layout_marginRight="22dp" 
    android:layout_marginEnd="22dp" /> 
+2

versuchen Changi ng getApplicationContext() zu YourActivity.this –

Antwort

1

Versuchen Sie dies mein Freund

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
+0

Einfach und unkompliziert. Habe es einfach versucht und es funktioniert wie ein Zauber. –

+1

Vielen Dank für Ihre Nachricht! –

3

Versuchen Sie, getApplicationContext(), um YourActivity.this

public void teacherLogin(View view) 
{ 

AlertDialog.Builder alert = new 
AlertDialog.Builder(YourActivity.this); 
alert.setTitle("Login"); 
alert.setPositiveButton("Login", new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialogInterface, int i) { 

     Toast.makeText(YourActivity.this, "you clicked login", 
     Toast.LENGTH_SHORT).show(); 

    } 
}); 
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
{ 
    @Override 
    public void onClick(DialogInterface dialogInterface, int i) { 
     Toast.makeText(YourActivity.this, "Cancelled", 
     Toast.LENGTH_SHORT).show(); 
    } 
}); 

AlertDialog dialog = alert.create(); 
dialog.setCancelable(false); 
dialog.setCanceledOnTouchOutside(false); 
dialog.show(); 
}