当我想从android中的Alert框中检索一个值时,它会在我点击OK按钮之前返回。
这是我做的功能:
public String enterSecretCode(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Secret Code");
alert.setMessage("Enter your 5 digit Secret Code to Encode!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(5)});
input.setHint("XXXXX");
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
code = input.getText().toString();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return code;
}
这是函数调用,我试图在点击按钮时找借口:
String secretCode = enterSecretCode();
答案 0 :(得分:0)
show()
不是阻止通话。您需要重写代码以将结果作为正按钮onClick()
方法的一部分进行处理,而不是让此方法返回一些值。
答案 1 :(得分:0)
如果您愿意,可以使用界面:
创建一个名为AlertInterface的新类
public class AlertInterface {
Context context;
Receiver receiver;
public AlertInterface(Context context, Receiver receiver)
{
this.context=context;
this.receiver=receiver;
}
public void enterSecretCode()
{
final AlertDialog.Builder alert = new AlertDialog.Builder(this.context);
alert.setTitle("Secret Code");
alert.setMessage("Enter your 5 digit Secret Code to Encode!");
// Set an EditText view to get user input
final EditText input = new EditText(this.context);
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(5)});
input.setHint("XXXXX");
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String code = input.getText().toString();
receiver.onLoad(code);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
public interface Receiver{
void onLoad(String code);
}
}
要调用此类,请在您的Activity中添加:
AlertInterface aux=new AlertInterface(MainActivity.this, new AlertInterface.Receiver() {
public void onLoad(String code) {
Toast.makeText(MainActivity.this,"Secret code entered: "+code,Toast.LENGTH_LONG).show();
}
});
aux.enterSecretCode();
结果将在Activity中的onLoad实现方法中接收。