我想编写一个函数,显示一个警告对话框,根据点击的按钮返回布尔值
private Boolean ShowWarningMessageBox(String Title, String message)
{
boolean returnValue = false;
AlertDialog.Builder builder = new AlertDialog.Builder(
getApplicationContext());
builder.setTitle(Title);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
returnValue = true;
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
returnValue = false;
}
});
builder.show();
return returnValue;
}
我编写了上面的函数,但问题是,Inner类将无法访问returnValue变量,因为它不是final。但是让它成为最终的并不符合我的目的。
我是一名c#开发人员,我正在尝试在android
中实现类似下面的内容private DialogResult ShowWarningMessageBox(string errorMessage)
{
DialogResult result = MessageBox.Show(errorMessage,
Resources.WarningCaption.ToString(),
MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button1);
return result;
}
任何帮助将不胜感激
答案 0 :(得分:7)
完整解决方案试试这个
1)创建界面
import android.content.DialogInterface;
public interface AlertMagnatic {
public abstract void onButtonClicked(boolean value);
}
2)确认对话框的通用方法。
public static void getConfirmDialog(final Context mContext,
final String title, final String msg,
final String positiveBtnCaption, final String negativeBtnCaption,
final boolean isCancelable, final AlertMagnatic target) {
((Activity) mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.ic_dialog_alert;
Drawable image = mContext.getResources().getDrawable(
imageResource);
builder.setTitle(title)
.setMessage(msg)
.setIcon(image)
.setCancelable(false)
.setPositiveButton(positiveBtnCaption,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
target.onButtonClicked(true);
}
})
.setNegativeButton(negativeBtnCaption,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
target.onButtonClicked(false);
}
});
AlertDialog alert = builder.create();
alert.setCancelable(isCancelable);
alert.show();
if (isCancelable) {
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
target.onButtonClicked(false);
}
});
}
}
});
}
3)如何使用
getConfirmDialog(getString(R.string.logout), getString(R.string.logout_message), getString(R.string.yes), getString(R.string.no), false,
new AlertMagnatic() {
@Override
public void onButtonClicked(boolean value) {
}
});