Reputation: 2439
I have a class which serves as my model.
class Model {
String name;
String address;
}
I have an array of objects of this class with 'n' elements.
List<Model> modelElements;
I am trying to implement a ViewPager with 'n' number of Fragments. Each fragment in the ViewPager is exactly the same but the data shown is picked from each element of the Model. I have implemented a basic Fragment which has two TextViews, each for showing the name and address.
I want to know how can I pass the object of Model class to each Fragment. So modelElements[0] corresponds to the first Fragment in ViewPager, modelElements[1] corresponds to the second Fragment and so on.
One way could be to use Bundle. But the way ViewPager creates Fragments doesn't expose me to the FragmentTransaction.
class MyViewPagerAdapter extends FragmentStatePagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
if (i == 0) {
return MyFragment.newInstance();
} else if (i == 1) {
return MyFragment.newInstance();
} else if (i == 2) {
return MyFragment.newInstance();
}
return null;
}
}
What is the best way to pass the data?
Also, this sounds stupid to me - create a new instance of the same Fragment for each set of different data. Is there some other construct that Android offers that will fit my requirement?
Upvotes: 2
Views: 989
Reputation: 11194
Below is Demo code i hv created to load different url in viewpage dynamically , however the there are dynamic urls passed to eachview in viewpage like below :
// ... do other initialization, such as create an ActionBar ...
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById(R.id.view_pager);
pager.setAdapter(pagerAdapter);
WebView w1 = new WebView(MainActivity.this);
w1.setWebViewClient(new WebViewClient());
w1.loadUrl("http://www.google.com");
WebView w2 = new WebView(MainActivity.this);
w2.setWebViewClient(new WebViewClient());
w2.loadUrl("http://www.live.com");
pagerAdapter.addView(w1, 0);
pagerAdapter.addView(w2, 1);
Upvotes: 0
Reputation: 18977
1) Make your Model implement Parcelable interface.
2) Pass your model to newInstance()
so it becomes newInstance(Model model)
3) In the newInstance()
create bundle and set the argument for your fragment with a value of model
4) Retrieve the model from onCreate
of the fragment
Upvotes: 1