如何使用startActivityForResult管理活动 [英] How to manage activity with startActivityForResult

查看:50
本文介绍了如何使用startActivityForResult管理活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况:

活动A-> B-> C-> D,当D完成后,我必须刷新ActivityA才能显示我在ActivityB,ActivityC和ActivityD中输入的内容.这是我的代码:

Activity A --> B --> C --> D, when D finished, I have to refresh ActivityA to display what I input in ActivityB , ActivityC and ActivityD.Here is my code:

ActivityA

ActivityA

    @OnClick(R.id.btn_one)
    public void toActivityB(){
        Intent intent = new Intent();
        intent.setClass(this, ActivityB.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){
            String b = data.getStringExtra("b");
            String c = data.getStringExtra("c");
            String d = data.getStringExtra("d");
            tvAll.setText(etOne.getText().toString() + "\n" + b + "\n" + c + "\n" + d);
        }
    }

活动B

    @OnClick(R.id.btn_two)
    public void toActivityC(){
        Intent intent = new Intent();
        intent.setClass(this, ActivityC.class);
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK){
            data.putExtra("b", etTwo.getText().toString());
            setResult(RESULT_OK, data);
            finish();
        }
    }

ActivityC代码类似于ActivityB,最后一个ActivityD如下:

ActivityC code just like ActivityB, the last ActivityD as follow:

    @OnClick(R.id.btn_four)
    public void returnToActivityA(){
        Intent intent = new Intent();
        intent.putExtra("d", etFour.getText().toString());
        setResult(RESULT_OK, intent);
        finish();
    }

这样,我可以在ActivityB,ActivityC,ActivityD中获取输入值,但是我必须在每个Activity上重写方法onActivityResult并逐个处理数据.处理这种情况?有什么好的建议,我将不胜感激.

In this way, I can get the input value in ActivityB,ActivityC,ActivityD.but I have to override the method onActivityResult at every Activity and handle the data one by one.Is there any another easy way for me to handle this situation?Any good suggestion I'll be appreciate.

推荐答案

您可以将目标" Activity传递给所需的结果,从一个Activity传递到下一个Intent.FLAG_ACTIVITY_FORWARD_RESULT.例如,如果您启动 ActivityC :

You can pass on the "target" Activity for the required results from one Activity to the next with Intent.FLAG_ACTIVITY_FORWARD_RESULT. If you start ActivityC for example:

@OnClick(R.id.btn_two)
public void toActivityC(){
    Intent intent = new Intent();
    intent.setClass(this, ActivityC.class);
    intent.setFlag( Intent.FLAG_ACTIVITY_FORWARD_RESULT );
    startActivityForResult(intent, 2);
}

这样,新活动可以调用setResult(int)并将结果发送回原始活动的回复目标.

This way the new activity can call setResult(int) and have that result sent back to the reply target of the original activity.

(引自Intent 文档)

在您的情况下,这还意味着每个Activity( B C )都必须将到目前为止收集的数据与Intent一起传递用于启动下一个Activity.最后, ActivityD 可以调用setResult()将数据传输到 ActivityA .

In your case this means also that each Activity (B and C) has to pass the data which has been collected so far along with the Intent used for starting the next Activity. Finally, ActivityD can call setResult() to transmit the data to ActivityA.

编辑(1)我要添加一些代码来演示如果用户按下BACK键该如何反应.为简单起见,我们假设用户只决定在 ActivityD 时按下BACK.

EDIT (1) I'm adding some code to demonstrate how to react if the user presses the BACK key. For simplicity's sake, let's assume that the user would only decide to press BACK while in ActivityD.

编辑(2)注意,Intent.putExtra()可以取一个Bundle,因此您可以将所有数据一起传递给整个Bundle,而不是将所有值一一传递给新的Intent.使用一个额外的Bundle而不是其他几个额外的内容可能会导致更少的代码行.

EDIT (2) Note that Intent.putExtra() can take a Bundle, so you can pass a whole Bundle with all your data along instead of transferring all the values one by one to the new Intent. Using one Bundle extra instead of several other extras can result in less lines of code.

xml文件

activity_a.xml

activity_a.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    <TextView
        android:text="Results:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:id="@+id/tv_result1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <TextView
        android:id="@+id/tv_result2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <TextView
        android:id="@+id/tv_result3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get results!"/>

</LinearLayout>

activity_b.xml

activity_b.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"
        android:text="Forwarding Results"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get more results!"/>

</LinearLayout>

activity_c.xml

activity_c.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff00ff"
        android:text="is"
        android:checked="true"
        android:id="@+id/cb_result"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get more results!"/>

</LinearLayout>

activity_d.xml

activity_d.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000ff"/>

    <Button
        android:id="@+id/btn_send_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send all results!"/>

</LinearLayout>

活动

ActivityA

ActivityA

public class ActivityA extends AppCompatActivity
{
    static final int REQUEST_CODE = 42;

    static final String KEY_RESULT_FROM_B = "result_b";
    static final String KEY_RESULT_FROM_C = "result_c";
    static final String KEY_RESULT_FROM_D = "result_d";

    private TextView tvResult1, tvResult2, tvResult3;
    private Button btnGetResults;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a);

    tvResult1 = (TextView) findViewById(R.id.tv_result1);
    tvResult2 = (TextView) findViewById(R.id.tv_result2);
    tvResult3 = (TextView) findViewById(R.id.tv_result3);

    btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivityForResult(new Intent(ActivityA.this, ActivityB.class), REQUEST_CODE);
        }
    });

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (REQUEST_CODE == requestCode)
    {
        if (resultCode == RESULT_OK)
        {
            tvResult1.setText(data.getStringExtra(KEY_RESULT_FROM_B));
            tvResult2.setText(data.getStringExtra(KEY_RESULT_FROM_C));
            tvResult3.setText(data.getStringExtra(KEY_RESULT_FROM_D));
            btnGetResults.setEnabled(false);
        }
        else
        {
            Toast.makeText(ActivityA.this, "no result", Toast.LENGTH_SHORT).show();
            // do something else
        }
    }
}
}

活动B

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    TextView tvResult = (TextView) findViewById(R.id.tv_result);
    final String result = tvResult.getText().toString();

    Button btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(ActivityB.this, ActivityC.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);

            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result);
            startActivity(intent);
            finish();
        }
    });
}

ActivityC

ActivityC

public class ActivityC extends AppCompatActivity
{
    static final String IS ="is";
    static final String IS_NOT = "is not";

    private CheckBox cbResult;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_c);

    cbResult = (CheckBox) findViewById(R.id.cb_result);
    cbResult.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            buttonView.setText(isChecked ? IS : IS_NOT);
        }
    });

    String previousResult = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_C);
    cbResult.setChecked( ! IS_NOT.equals(previousResult) );

    final String result1 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_B);

    Button btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(ActivityC.this, ActivityD.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
            String result2= cbResult.getText().toString();
            intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
            startActivity(intent);
            finish();
        }
    });
}
}

ActivityD

ActivityD

public class ActivityD extends AppCompatActivity
{
    static final String POSSIBLE = "possible :)";
    static final String COMPLICATED = "complicated";

    private String result1, result2;

    private TextView tvResult;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_d);

    tvResult = (TextView) findViewById(R.id.tv_result);
    result1 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_B);
    result2 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_C);

    if (ActivityC.IS.equals(result2))
    {
        tvResult.setText(POSSIBLE);
    }
    else
    {
        tvResult.setText(COMPLICATED);
    }


    Button btnSendResults = (Button) findViewById(R.id.btn_send_results);
    btnSendResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent();

            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_D,  tvResult.getText().toString());
            setResult(RESULT_OK, intent);
            finish();
        }
    });
}

@Override
public void onBackPressed()
{
    // start ActivityC once more
    Intent intent = new Intent(ActivityD.this, ActivityC.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);

    intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
    // pass this to set the CheckBox like the user left it:
    intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
    startActivity(intent);
    finish();
}
}

这篇关于如何使用startActivityForResult管理活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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