这是本书样本中的代码:
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();
单独的语句,每个语句都在一个普通的生成器对象上执行。
或者,可以使用链式生成器方法来保存一些字符(如原始源代码),但可以编写可读性更强的方法。为此,请删除每行开头的分号和对象引用。每个builder方法都返回原始的builder对象,您可以使用该对象在其上运行下一条语句。
下面是一个小的、可读性更好的例子:
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("42 is the answer")
.show();