从 Activity 到 Fragment 获得结果

就像从另一个 Activity 获取结果一样,你需要调用 Fragment 的方法 startActivityForResult(Intent intent, int requestCode) 。请注意,你不应该调用 getActivity().startActivityForResult(),因为这会将结果返回给 Fragment 的父母 Activity

接收结果可以使用 Fragment 的方法 onActivityResult() 完成 。你需要确保 Fragment 的父 Activity 还覆盖 onActivityResult()并调用它的 super 实现。

在以下示例中,ActivityOne 包含 FragmentOne,它将启动 ActivityTwo 并期望得到它的结果。

ActivityOne

public class ActivityOne extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
    }

    // You must override this method as the second Activity will always send its results to this Activity and then to the Fragment
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
    }
}

activity_one.xml

<fragment android:name="com.example.FragmentOne"
    android:id="@+id/fragment_one"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

FragmentOne

public class FragmentOne extends Fragment {
    public static final int REQUEST_CODE = 11;
    public static final int RESULT_CODE = 12;
    public static final String EXTRA_KEY_TEST = "testKey";

    // Initializing and starting the second Activity
    private void startSecondActivity() {
        Intent intent = new Intent(getActivity(), ActivityTwo.class);
        startActivityForResult(REQUEST_CODE, intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE) {
            String testResult = data.getStringExtra(EXTRA_KEY_TEST);
            // TODO: Do something with your extra data
        }
    }
}

ActivityTwo

public class ActivityTwo extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
    }

    private void closeActivity() {
        Intent intent = new Intent();
        intent.putExtra(FragmentOne.EXTRA_KEY_TEST, "Testing passing data back to ActivityOne");
        setResult(FragmentOne.RESULT_CODE, intent); // You can also send result without any data using setResult(int resultCode)
        finish();
    }
}