【发布时间】:2012-08-29 02:47:01
【问题描述】:
我已经搜索了答案,但没有找到,所以请帮助我:)
我有一个自定义类:
public class CustomClass {
private final Context ctx;
public CustomClass(Context ctx) {
this.ctx = ctx;
}
public boolean setDialog(int head, int text) {
final boolean value;
final Dialog d = new Dialog(ctx);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.custom2_dialog);
TextView txtHead = (TextView) d.findViewById(R.id.custom2_txtHead);
txtHead.setText(ctx.getResources().getString(head));
TextView txtText = (TextView) d.findViewById(R.id.custom2_txtText);
txtText.setText(ctx.getResources().getString(text));
Button btnOK = (Button) d.findViewById(R.id.custom2_btnOK);
btnOK.setText("OK");
btnOK.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
value = true;
d.dismiss();
}
});
Button btnNO = (Button) d.findViewById(R.id.custom2_btnNO);
btnNO.setText("NO");
btnNO.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
value = false;
d.dismiss();
}
});
d.show();
return value;
}
}
您可以看到我在自定义类中创建了一个自定义对话框,因为我不想在每个活动中都创建一个对话框。现在当我在 Activity 中使用它时:
CustomClass cC = new CustomClass(this);
if(cC.setDialog(R.string.head, R.string.text)) {
// user checked OK
} else {
// user checked NO
}
如何知道用户是否勾选了 OK 或 NO,因为返回 true、false 值在自定义类中不起作用,对话框不会在用户点击之前等待,它会自动返回一个值。
【问题讨论】:
-
Simple Buddy,而不是为对话框创建自定义类使用
Application类定义相同的方法,但方法setDialog()返回Void并全局声明变量boolean value,现在你可以获取用户选择的任何地方。 -
Application 类最好的一点是你不需要在每次显示 Dialog 时都传递当前 Activity 的上下文。
-
无法同步获取返回值。您将不得不使用监听器
-
@user370305 我不知道你是什么意思 return void,当我将方法从 boolean 更改为 void 时,我不能返回任何东西,你有一个例子吗?
-
你不需要返回值。仔细阅读我的第一条评论..