如何将值从一个活动传递到前一个活动 [英] How to pass the values from one activity to previous activity

查看:23
本文介绍了如何将值从一个活动传递到前一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将值从一个屏幕传递到前一个屏幕?

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.

如果我单击第一个按钮,则它必须移动到第二个活动,并且用户必须在此处在文本框中键入一些内容.如果他从第二个屏幕按下按钮,则文本框中的值应移至第一个活动,并应显示在第一个活动 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.

推荐答案

要捕获在另一个 Activity 中执行的操作需要三个步骤.

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

在子活动中,您需要创建一个新的 Intent 并将输入的文本值包含在它的附加包中,而不仅仅是在用户单击按钮时关闭该 Activity.在调用 finish 以关闭辅助 Activity 之前,将其传递回父调用 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.

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

最后一步是在调用 Activity:覆盖 onActivityResult 以监听来自文本条目 Activity 的回调.从返回的 Intent 中获取额外的内容以获取您应该显示的文本值.

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

这篇关于如何将值从一个活动传递到前一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆