How To Get Data From Fragments In The Parent Activity?
This is my Parent Activity containing a tab layout and view pager and a button at the bottom:
Now suppose you have Fragment1 and you want to access data and validate it. Use,
Fragment1 f1= (Fragment1) viewPager
.getAdapter()
.instantiateItem(viewPager, position);
Now you need to create validate()
method in Fragment1
so you can access that method by,
f1.validate();
Before you call f1.validate(); check that if(f1!=null) && f1.isVisible()
and then access data from it and do same for Fragment2
.
Solution 2:
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.
Here is an example of Fragment to Activity communication:
publicclassHeadlinesFragmentextendsListFragment {
OnHeadlineSelectedListener callback;
publicvoidsetOnHeadlineSelectedListener(OnHeadlineSelectedListener callback) {
this.callback = callback;
}
// This interface can be implemented by the Activity, parent Fragment,// or a separate test implementation.publicinterfaceOnHeadlineSelectedListener {
publicvoidonArticleSelected(int position);
}
// ...
}
MainActivity
publicstaticclassMainActivityextendsActivityimplementsHeadlinesFragment.OnHeadlineSelectedListener{
@OverridepublicvoidonAttachFragment(Fragment fragment) {
if (fragment instanceof HeadlinesFragment) {
HeadlinesFragmentheadlinesFragment= (HeadlinesFragment) fragment;
headlinesFragment.setOnHeadlineSelectedListener(this);
}
}
}
For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
@OverridepublicvoidonListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
callback.onArticleSelected(position);
}
Hope it works for you.
Post a Comment for "How To Get Data From Fragments In The Parent Activity?"