如何从第二个活动月1日活动传递数据时,pressed回来? - 机器人第二个、机器人、数据、pressed

2023-09-12 23:42:48 作者:-告别-爱过的你

我有2活动,活动1 和活性2

活动1 我有一个按钮和的TextView 。 当按钮被点击活性2 已启动。

In Activity1 i've a button and textview. When button is clicked Activity2 is started.

活性2 我的 editext

我希望显示的 editext 在活性2 在的TextView 在活动1 :当回被检索的数据从pssed $ P $ 活性2

I want to display the data retrieved from editext in Activity2 in the textview in Activity1 when back is pressed from Activity2.

有人可以帮助我的code,使这项工作?

can someone help me with the code to make this work?

推荐答案

开始你的第二个活动是startActivityForResult并使用的setResult()方法将数据发送回从活性2到活动1。在相关活动,你将需要重写 onActivityResult 从活性2更新的TextView与EditText上的数据

Start your Second Activity as startActivityForResult and use setResult() method for sending data back from Activity2 to Activity1. In activity1 you will need to Override onActivityResult for Updating TextView with EditText data from Activity2

例如:

开始活性2从Acivity1为:

Start Activity2 from Acivity1 as:

Intent i = new Intent(this,  Activity2.class);
startActivityForResult(i, 1);

在活性2使用的setResult 将数据发送回:

in Activity2 use setResult for sending data back :

Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here")
setResult(RESULT_OK, intent);        
finish();

在第一个活动接收数据onActivityResult:

and in First Activity receive data as onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK){
          String stredittext=data.getStringExtra("edittextvalue");
    }
} 

如果你可以使用Shared$p$pferences也为共享活动之间的数据。

and if you can use SharedPreferences also for Sharing data Between Activities