4.1 communication in activity

Keywords: Fragment

Scenario 1: ActivityA starts ActivityB

1, Method of transferring data from Activity A to activity B

  1. Through Intent's Bundle
Intent intent = new Intent(ActivityA.this,ActivityB.class);
Persion p = new Persion("tang","man");
Bundle b = new Bundle();
b.putSerializable("persion",p);
intent.putExtras(b);
startActivity(intent);

2, Method to return the result to ActivityA after ActivityB processing

Start Activity in ActivityA with the following code

startActivityForResult(intent,int requestCode);
//You also need to override the onActivityResult method to process the returned results
public void onActivityResult(int requestCode,int resultCode,Intent intent){
    //...
}

Return the result in ActivityB as follows:

Intent intent = getIntent();
intent.putExtra("city","changsha");
ActivityB.this.setResult(0,intent);
ActivityB.this.finish();

Scenario 2 communication between activity and Fragment

1, Get corresponding components

getActivity()
getFragmentManager().findFragmentById();

2, Transfer data
1. Activity transfers data to Fragment

Bundle bundle = new Bundle();
bundle.putInt("id",78);
FragmentA fragment = new FragmentA();
fragment.setArguments(bundle);
// Use fragment to replace the FrameLayout with the id of book detail container
getFragmentManager().beginTrasaction().replace(R.id.book_detail_container,fragment);
  1. Fragment passes data to Activity
    Build an interface in Fragment and call
pulbic class FragmentA extends Fragment{
    pulbic interface Callbacks{
        pulbic void onItemSelected(Integer i);
    }
    //Convert Activity to callbacks in onattach (method)
    public void onAttach(Activity activity){
        mCallbacks = (Callbacks) activity;
    }
    //In other ways, data transfer is realized by calling
    public void diaoyong(){
        mCallbacks.onItemSelected(15);
    }
}

Implement the interface in FragmentA in Activity, and the call above becomes the call Activity

Posted by Chafikb on Sun, 05 Jan 2020 06:16:03 -0800