【发布时间】:2013-03-21 10:08:17
【问题描述】:
我可以将变量设置为 web 开发中的会话等上下文吗?
这是我的代码,一旦 Android 应用程序启动,我将在其中开发一个确认框:
package com.example.alertboxandloadingwidgets;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Boolean result = showConfirmationBox("Are you sure you want to do this",
this);
}
public Boolean showConfirmationBox(String messageToShow, final Context context) {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
// set the message to display
alertbox.setMessage(messageToShow);
// set a positive/yes button and create a listener
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(context,
"'Yes' button clicked", Toast.LENGTH_SHORT)
.show();
}
});
// set a negative/no button and create a listener
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(context, "'No' button clicked",
Toast.LENGTH_SHORT).show();
}
});
// display box
alertbox.show();
}
}
但我希望如果单击yes 按钮,则它必须返回true,如果单击no 按钮,则它必须返回false。
但我不能这样做,因为onClickListener 的返回类型是无效的。
更新
但问题是我已将其设为通用意味着此方法我必须在 CommonUtilities 类中编写,其中任何活动都可以使用此方法。所以我必须设置或重置我调用此方法的结果参数的值。
【问题讨论】:
-
你不能这样做。 Android 对话框是异步的,因此您需要相应地重构代码。
-
那么我必须允许什么方法意味着我应该在首选项中有一些通用参数。所以我必须设置或重置它的值。
-
你想错了。在 android 没有办法 做一个同步阻塞警报对话框。你必须重构它。一种方法是使用活动而不是对话框;调用它以获得结果并根据单击的按钮返回不同的结果;然后处理
onActivityResult中的结果。相信我,如果可能的话,Android 会在标准 API 中进行这样的调用。
标签: java android android-widget