我目前正在构建一个应用程序,我正面临一个持久性问题。 我有2个活动A和B.在A中我定义信息'aa'和B信息'bb'('aa'通过意图提供给B)。当在B中并通过导航后退按钮(在操作栏中)回到A时,我希望A能够访问'bb'值,以便我可以基于它执行某些逻辑。对于你来说,保持这些数据在A中访问它的最佳方法是什么? 在此先感谢您的时间和帮助。 干杯, 本杰明
答案 0 :(得分:1)
您可以尝试使用onActivityResult。
在活动B中:
@Override
public void onBackPressed() {
// super.onBackPressed();
Intent intent = new Intent();
//put something in intent
setResult(RESULT_OK, intent);
finish();
}
在活动A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
//get extra...
}
}
}
答案 1 :(得分:0)
从活动A启动活动B时,请使用startActivityForResult(Intent, int);
代替正常startActivity(Intent);
并覆盖活动A中的onActivityResult()
例如
public class ActivityA extends Activity{
private static final int MY_REQUEST_CODE = 123;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//Setup your activity and views...
//Assuming that you start ActivityB when a button is clicked.
btnExample.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent(ActivityA.this, ActivityB.class);
//Setup your intent and put the data.
startActivityForResult(intent, MY_REQUEST_CODE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent backIntent)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == MY_REQUEST_CODE && backIntent != null){
//Handle your logic here.
}
}
}
并在活动B中,覆盖onBackPressed
public class ActivityB extends Activity{
//Setup your activity
@Override
public void onBackPressed()
{
Intent backIntent = new Intent();
//Put the data to backIntent
setResult(RESULT_OK, backIntent);
super.onBackPressed();
}
//The rest of your code
}