Activity 与 Fragment 通信方式

在Android中我们可以通过以下几种方式实现Activity和fragment之间的通信:
  • Handler
  • 广播
  • EventBus
  • 接口回调
  • Bundle和setArguments(bundle)
记录Fragment && Fragment 通过setTargetFragment数据交互:
public class TargetAFragment extends Fragment {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.findViewById(R.id.sendMSG).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendResult(RESULT_OK);
            }
        });
    }

    private void sendResult(int resultOk) {
        if(getTargetFragment() != null){
            Intent intent = new Intent();
            intent.putExtra("key", 1024);
            getTargetFragment().onActivityResult(TargetBFragment.REQUEST_CODE,resultOk,intent);
        }
    }
}
public class TargetBFragment extends Fragment {
    public static final int REQUEST_CODE = 1001;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Activity activity = getActivity();
        if (activity != null) {
            if (activity instanceof TargetHost1Activity) {
                ((TargetHost1Activity) activity).targetAFragment.setTargetFragment(TargetBFragment.this, REQUEST_CODE);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            Integer str = data.getIntExtra("key", -1);
            //do Something
        }
    }

}

你可能感兴趣的:(Android,通信)