2017-10-07 127 views
-2

我是新來的android開發領域,所以嘗試了AlertDialog框,我有麻煩了。 這是我的部分代碼AlertDialog我的快速對話不起作用?

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(); 
} 

這裏是Button我的XML代碼調用teacherLogin()方法

<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

嘗試changi ng getApplicationContext()到YourActivity.this –

回答

1

試試這個我的朋友

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

簡單而直接。剛試過這個,它就像一個魅力。 –

+1

謝謝你的提示! –

3

嘗試改變getApplicationContext()來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(); 
}