從 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();
    }
}