如何从一个活动中的值传递到previous活动活动中、previous

2023-09-11 12:25:35 作者:8.花败ヽ亦残缺

我如何传递一个值从一个屏幕到previous屏?

How do I pass a value from one screen to its previous screen?

考虑这种情况下:我有两个活动。第一个屏幕上有一个的TextView 和一个按钮,第二活动有一个的EditText 和一个按钮。

Consider this case: I have two activities. The first screen has one TextView and a button and the second activity has one EditText and a button.

如果我点击第一个按钮,然后它移动到第二个活动在这里用户键入的东西在文本框中。如果他presses从第二个屏幕的按钮,然后从文本框的值应该移动到第一个活动,并应显示在第一个活动的TextView

If I click the first button then it has to move to second activity and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first activity and that should be displayed in the first activity TextView.

推荐答案

要捕捉的动作在上一个又一个的活动执行需要三个步骤。

To capture actions performed on one Activity within another requires three steps.

通过启动辅助活动(你的编辑文本活动)作为子活动 startActivityForResult 从您的主要活动。

Launch the secondary Activity (your 'Edit Text' Activity) as a subactivity by using startActivityForResult from your main Activity.

Intent i = new Intent(this,TextEntryActivity.class);    
startActivityForResult(i, STATIC_INTEGER_VALUE);

在子活动,而不仅仅是关闭活动,当用户点击该按钮,你需要创建一个新的意图,并作为其额外的包中输入的文本值。要调用完成关闭辅助活动之前回来把它传递给父调用的setResult

Within the subactivity, rather than just closing the Activity when a user clicks the button, you need to create a new Intent and include the entered text value in its extras bundle. To pass it back to the parent call setResult before calling finish to close the secondary Activity.

resultIntent = new Intent(null);
resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, enteredTextValue);
setResult(Activity.RESULT_OK, resultIntent);
finish();

最后一步是在调用活动,覆盖 onActivityResult 来侦听来自文本输入活动回调。获得额外的从返回的意图,让您应该显示的文本值。

The final step is in the calling Activity, override onActivityResult to listen for callbacks from the text entry Activity. Get the extra from the returned Intent to get the text value you should be displaying.

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) {     
  super.onActivityResult(requestCode, resultCode, data); 
  switch(requestCode) { 
    case (STATIC_INTEGER_VALUE) : { 
      if (resultCode == Activity.RESULT_OK) { 
      String newText = data.getStringExtra(PUBLIC_STATIC_STRING_IDENTIFIER);
      // TODO Update your TextView.
      } 
      break; 
    } 
  } 
}