1. 程式人生 > >(8)呼叫Fragment自身的startActivityForResult並在Fragment中接收返回結果

(8)呼叫Fragment自身的startActivityForResult並在Fragment中接收返回結果

package com.xzy.fragmentbasicdemo.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.xzy.fragmentbasicdemo.ContentActivity;
import com.xzy.fragmentbasicdemo.R;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContentFragment extends Fragment {
    private static final String TAG = "ContentFragment";

    private static final int REQUEST_CODE = 0x11;


    public ContentFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content, container, false);
        Button button = view.findViewById(R.id.btn_test);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ContentActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                return;
            }
            if (data != null) {
                /**
                 * 取參
                 * */
                int param = data.getIntExtra("test", 0);
                Log.i(TAG, "onActivityResult: param:" + param);
            }
            Log.i(TAG, "onActivityResult: resultCode" + resultCode + ",requestCode:" + requestCode);
            //do something
        }
    }
}
ContentActivity