In android,Activity and Fragment are both important UI components that us----programer to program against and users to interact with machine.In other words,Activity and Fragment are the platform of operation of android APP.
So ,there is an important question.how can the two kind of objects communicate with each other?
To begin with,let’s take a look at how to open a Fragment from Activity.
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();//--------1
fragmentTransaction.replace(R.id.fragment_container,fragment1);//-------------------2
fragmentTransaction.commit();//-----------------------------------------------------3
Remember,if you want to open a Fragment after clicking a button,you’d better move the sentence 1,2,3 to the onClickListener block.If you don’t do that,and beginTransaction() only once at the onCreat() method ,after you click the button at the second time,you will get an Exception that “the commit() has been called”.
Since you have opened a Fragment.How to put data to the Fragment?
Well,it’s quite easy,right?Because you have already hold the Fragment’s reference,you can put any data you want to the fragment.
In the Fragment’s Java file ,you can create
public void putArguments(Bundle data)
{
bundle=data;
}
Whenever you want put data,you just invoke the method from Activity Java file.
Since you have known how to put data to a fragment.How to put data back to Activity?
From the perspective of philosophy,if you want communicate with a subject,you have to know the subject.Here,the first problem we have to solve is how to get the reference of the Activity.
Well,we can use
getActivity();
This method is useful.It returns back the reference of the Activity that the Fragment depends on.
You know what to do next,right?
((MainActivity)getActivity());
cast the type from top to bottom.This is agreed by Java,because the process is just
MainActivity-----(getActivity)------>Activity------((MainActivity)getActivity)---->MainActivity
Now,you can get whatever you want through the reference of MainActivity!