AlertDialog每次我想使用它時都進行初始化非常無聊,我有很多使用的活動,AlertDialog所以我想簡化它并創建一個類來初始化AlertDialog并在我想要的時候顯示它。
這是DialogManager我創建的類:
public class DialogManager {
private static AlertDialog.Builder builder;
public static void show(Context context, int themeResId, String title, String message, String positiveButtonText) {
builder = new AlertDialog.Builder(context, themeResId)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonText, null);
builder.show();
}
public static void show(Context context, int themeResId, String title, String message, String positiveButtonText, String negativeButtonText) {
builder = new AlertDialog.Builder(context, themeResId)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonText, null)
.setNegativeButton(negativeButtonText, null);
builder.show();
}
}
一切正常,但我遇到了點擊監聽器的問題,我該如何處理點擊監聽器,因為每個活動都會以它的方式處理按鈕。
我該如何處理?
uj5u.com熱心網友回復:
setPositiveButtonDialogInterface.OnClickListener作為第二個引數,所以只需將其添加為方法引數
public static void show(Context context, int themeResId, String title, String message,
String positiveButtonText,
DialogInterface.OnClickListener positiveCallback) {
show(context, themeResId, title, message,
positiveButtonText, positiveCallback,
null, null); // no negative in this case
}
public static void show(Context context, int themeResId, String title, String message,
String positiveButtonText,
DialogInterface.OnClickListener positiveCallback,
String negativeButtonText,
DialogInterface.OnClickListener negativeCallback) {
AlertDialog.Builder builder = new AlertDialog.Builder(context, themeResId)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonText, positiveCallback);
if (negativeButtonText!=null) {
builder.setNegativeButton(negativeButtonText, negativeCallback);
}
builder.show();
}
并且不要過度使用static關鍵字,保留static Builder此檔案的頂部不是正確的方法(在某些情況下,它可能會導致記憶體泄漏,也可能在您的情況下),因此請洗掉以下行并僅保留本地構建器直到您呼叫builder.show()
private static AlertDialog.Builder builder;
uj5u.com熱心網友回復:
setPositiveButton 將 DialogInterface.OnClickListener 作為第二個引數,因此只需將其添加為方法引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427338.html
下一篇:大O表示法和凱撒密碼
