Android - How To Pass Data From Activity To Fragment?
Solution 1:
Create one interface
in your Activity
and pass your data via the interface
to the fragment
. Implement that interface
in your fragment
to get data.
For example
MainActivity.class
publicclassMainActivityextendsAppCompatActivity {
DataFromActivityToFragment dataFromActivityToFragment;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentAfr=newFragmentA();
FragmentManagerfm= getFragmentManager();
dataFromActivityToFragment = (DataFromActivityToFragment) fr;
FragmentTransactionfragmentTransaction= fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
finalHandlerhandler=newHandler();
finalRunnabler=newRunnable() {
publicvoidrun() {
dataFromActivityToFragment.sendData("Hi");
}
};
handler.postDelayed(r, 5000);
}
publicinterfaceDataFromActivityToFragment {
voidsendData(String data);
}
}
FragmentA.class
publicclassFragmentAextendsFragmentimplementsMainActivity.DataFromActivityToFragment {
TextView text;
@Nullable@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_main, null);
text = (TextView) rootView.findViewById(R.id.fragment_text);
return rootView;
}
@OverridepublicvoidonViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@OverridepublicvoidsendData(String data) {
if(data != null)
text.setText(data);
}
}
activity_main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><LinearLayoutandroid:id="@+id/fragment_place"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"></LinearLayout></LinearLayout>
content_main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/fragment_text"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
In above example I have taken Runnable
just to send data with delay of 5 seconds after creation of fragment
.
Solution 2:
Fragment object is just like other objects.Like String , you can invoke methods of string object, str.charAt(0) ,str.toUpperCase() etc. Just create a function in fragment, put your code there and call the function along with values
Inside Activity {
fragDemoObject.doWhatYouWant("this is passed as string object to fragment");
}
Inside FragmentDemo{
void doWhatYouWant(String input){
System.out.println(input);
// do what else you want to do with code
}
}
Solution 3:
Actually your question is not related to:
I need to pass data from activity to fragmenet .I know I can use bundle , but one i've passed data , I cant send anymore data without calling and creating fragment once more .
The real one is this:
in my activity , some thing may be changed and I need to notify my fragment from these changes without recreating fragment.
how can I do so ?
In this case I would store the fragment in the activity as reference and I would call a function, an interface implementation inside the fragment.
Something like this:
In Activity:
SomeEventListener myFragment ;
yourFragmentCreationMethod(){
if(myFragment == null){
myFragment = newMyFragment(maybeParamsHere);
}
}
yourNotificationMethod(){
myFragment .onEventHappent(param);
}
// declare an interface: - separate filepublicinterfaceSomeEventListener
{
voidonEventHappent(param);
}
// implement the interface in Fragment - separate filepublicclassMyFragmentextendsFragmentimplementsSomeEventListener{
// add a constructor what you likepublicvoidonEventHappent(param){
/// ... your update
}
}
The interface it will help you at testing only.
Solution 4:
The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.
In your fragment - MyFragment
, create a public method
publicvoidmyFragmentDataFromActivity(int passedDataFromActivity){
// do your stuff
}
In your activity to pass an integer value say, 100 :
get MyFragment instance using getSupportFragmentManager or getFragmentManager by providing id/tag/position. Then call the public method in MyFragment instance.
MyFragment myFragment = (MyFragment) getSupportFragmentManager.getFragmentById(id);
myFragment.myFragmentDataFromActivity(100);
You can also use getFragmentByTag(tag)
, getFragments().get(position)
instead of getFragmentById(id)
to get fragment instance.
Solution 5:
For notify fragment with some data after it's created, can be done using some Communicator, or you can always pass the data with bundle in creation time... For example:
publicinterfaceFragmentCommunicator {
voidupdateDataToFragment(List<Parcelable> data);
} then in your fragment implement this interface and calling it from the activity for example as:`
Fragmentfragment= mSectionsPagerAdapter.getRegisteredFragment(i);
if (fragment instanceof FragmentCommunicator) {
FragmentCommunicatorfragmentCommunicator= (FragmentCommunicator) fragment;
fragmentCommunicator.updateDataToFragment(data);
}`
This should works for your case...
Post a Comment for "Android - How To Pass Data From Activity To Fragment?"