gpt4 book ai didi

android - 如何显示不同 Activity 的警报

转载 作者:行者123 更新时间:2023-11-30 03:24:18 26 4
gpt4 key购买 nike

我有一个 Activity 和第二个 Activity 。在第二个 Activity 中,我需要关闭 Activity ,然后然后再次向第一个 Activity 中的用户显示提醒。

这是我用来发出警报和关闭 Activity 的当前代码:

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();
}
});

那么我怎样才能使第二个 Activity finishes ,然后一旦回到第一个 Activity ,就向用户显示警报?

我也试过这个:

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

最佳答案

您需要使用 startActivityForResult() 方法来启动第二个 Activity 。然后,一旦第二个 Activity 关闭,就会调用第一个 Activity 的 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
...
}
}
}

关于android - 如何显示不同 Activity 的警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18526333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com