我有一个按钮,可以打开一个用于更改数字的对话框。该按钮处于活动状态,并生成一个新的类名对话框,用于存储不同的对话框。
Dialog consigna: Dialogs.class
public String consigna(){
AlertDialog.Builder alert = new AlertDialog.Builder(ctxt);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(ctxt);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data = input.getText().toString();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data;
}
点击按钮: MainActivity
//I need change these two values:
final public double temperatura = 200.3;
String newData;
...
public void onClick(View v) {
switch (v.getId()){
case R.id.tempConsigna:
dialog = new Dialogs(MainActivity.this);
String data = dialog.consigna();
newData = data;
break;
...//other cases...
问题在于newData = data;我没有数据,因为对话框没有关闭。该对话框在其他线程中工作,没有?
如何使用对话框结果更改newData var?它可以进入对话类吗?
答案 0 :(得分:2)
您需要通过接口实现回调方法:
public String consigna(final OnConfirm confirm){
final String[] data = new String[1];
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data[0] = input.getText().toString();
confirm.onConfirm(data[0]);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data[0];
}
public interface OnConfirm {
void onConfirm(String s);
}
并在您的主要活动中
Dialogs dialog = new Dialogs(MainActivity.this);
dialog.consigna(new Dialogs.OnConfirm() {
@Override
public void onConfirm(String s) {
Log.d("data", s);
}
});
答案 1 :(得分:0)
它不会返回你想要的结果但是在点击对话框确定按钮后然后访问数据变量。无需返回。