如何在不丢失文本字段内的文本的情况下返回最后的意图

时间:2013-01-07 11:53:05

标签: android android-intent

在我的程序中,有一些文本字段和一个打开相机意图的按钮。 (假设页面的名称是mainIntent)...让我们假设,用户填写文本字段并单击按钮; cameraIntent打开,用户拍摄照片..现在,我希望程序返回有文本字段和按钮的页面。但是如果我做的话

Intent i = new Intent(cameraIntent.this, mainIntent.class);
startActivity(i);

用户写的所有文本都消失了。我需要使用类似return mainIntent的东西,我想......

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要更改的应用程序状态值写入Bundle参数,如下所示:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

Bundle本质上是一种存储NVP(“名称 - 值对”)映射的方式,它将被传递到onCreate和onRestoreInstanceState,你可以在这里提取这样的值:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}

您通常使用此技术存储应用程序的实例值(选择,未保存的文本等)。

答案 1 :(得分:2)

在第一项活动中使用startActivityForResult。因此,您将能够返回呼叫活动。并且您不会丢失编辑文本的数据。

Intent i = new Intent(mainIntent.this, cameraIntent.class);
startActivityForResult(i, MY_REQ_CODE);

您可以为onActivityResult()添加此内容:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
      switch(requestCode) {
      case MY_REQ_CODE: 
            if (resultCode == RESULT_OK) {
                //Do action that's needed
                break;
            }

      }
}

在您的活动下一个活动中,您只需按以下方式拨打setResult()finish()即可。您无需在此处开始新活动:

Intent returnIntent = new Intent();
returnIntent.putExtra("ImageName",imgName);   //Required if you want to pass some data back
setResult(RESULT_OK,returnIntent);        
finish(); 

希望它有所帮助。