我有一项活动和第二项活动。在第二个活动中,我需要关闭活动,然后再次在第一个活动中向用户显示警报。
以下是我用于调出警报并关闭活动的当前代码:
String message = "message";
AlertDialog alertDialog = new AlertDialog.Builder(SecondActivity.this).create();
alertDialog.setMessage(message);
alertDialog.show();
alertDialog.setOnDismissListener(new OnDismissListener()
{
public void onDismiss(final DialogInterface dialog)
{
finish();
}
});
那么我怎样才能使第二个活动finishes
,然后一旦回到第一个活动,就会向用户显示警告?
我也尝试了这个:
String message = "message";
finish();
AlertDialog alertDialog = new AlertDialog.Builder(FirstActivity.class).create();
alertDialog.setMessage(message);
alertDialog.show();
但是我收到了这个错误:
The constructor AlertDialog.Builder(Class<FirstActivity>) is undefined
答案 0 :(得分:1)
您需要使用startActivityForResult()
方法启动第二项活动。然后,关闭第二个活动后,将调用第一个活动的onActivityResult()
方法。在那里你可以打开一个对话框。这是代码示例。
class SecondActivity extends Actvitiy {
// for instance you close your activity here
public void onClick(View view) {
// you have an int to get back
int resultValue = ...;
// store your variables into resulting intent
Intent data = new Intent();
data.putExtra(FirstActivity.EXT_RESULT, resultValue);
// store result with data
setResult(RESULT_OK, data);
// finish activity
finish();
}
}
class FirstActivity extends Activity {
public static final String EXT_RESULT = "result-value";
public static final int REQ_SECOND_ACTIVITY = 100;
// call this method to launch second activity
private void launchSecondActicity() {
startActivityForResult(
new Intent(this, SecondActivity.class), REQ_SECOND_ACTIVITY);
}
@Override
public onActivityResult(int requestCode, int resultCode, Intent data) {
// this gets called when second activity is closed
if (resultCode == RESULT_OK && requestCode == REQ_SECOND_ACTIVITY) {
// read your value
int resultValue = data.getIntExtra(EXT_RESULT, 0);
// open your dialog here
...
}
}
}
答案 1 :(得分:0)
我需要使用startActivityForResult
方法从第一个活动开始第二个活动,然后将result
从first activity
传递到second activity
。
Intent data = new Intent();
data.putExtra("reference for the message", message); // give the intent the String value to be passed to other activity
setResult(Activity.RESULT_OK, data);
finish();
将其放在first activity class
:
public static final int REQ_SECOND_ACTIVITY = 100;
这是从second activity
:
first activity
的方法
startActivityForResult(new Intent(FirstActivity.this, SecondActivity.class), REQ_SECOND_ACTIVITY);
最后,将此方法添加到first activity class
:
// this method gets called when the second activity is closed
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == REQ_SECOND_ACTIVITY)
{
String message = data.getStringExtra("reference for the message");
AlertDialog alertDialog = new AlertDialog.Builder(FirstActivity.this).create();
alertDialog.setMessage(message);
alertDialog.show();
}
}