这是本书示例中的代码:
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.alert_label))
.setMessage(validationText.toString())
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
})
.show();
我想看懂这段代码,请分几条语句改写,使每条语句恰好做一次操作。谢谢!
最佳答案
// Create a builder
AlertDialog.Builder adb = new AlertDialog.Builder(this);
// Set a title
adb.setTitle(getResources().getString(R.string.alert_label));
// Set the dialogs message
adb.setMessage(validationText.toString());
// Set label and even handling of the "positive button"
//
// NOTE: If you don't want to do anything here except to close the dlg
// use the next line instead (you don't have to specifiy an event handler)
// adb.setPositiveButton("Continue", null);
adb.setPositiveButton("Continue",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
// in this case, don't need to do anything other than close alert
}
});
// Show the dialog
adb.show();
单独的语句,每个语句都在一个普通的构建器对象上执行。
或者,您可以链接构建器方法以保存一些字符(如您的原始来源),但您可以将其编写得更具可读性。为此,请删除每行开头的分号和对象引用。每个构建器方法都会返回原始构建器对象,您可以使用该对象在其上运行下一条语句。
这里有一个小的、可读性更好的例子:
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("42 is the answer")
.show();
关于java - AlertDialog - 试图理解这种语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8151129/