I am trying to use ViewPager to implement a sliding system between a couple fragments I have. I have 2 fragments and 1 listfragment. How would I go about populating the viewpager with both of these types of fragments? Or would it be easier to implement a ListView in the fragment so I have 3 fragments?
I'm sorry I wasn't clear enough. I have 3 Fragments: 2 classes extend 'Fragment' while the third extends 'ListFragment'. In my ViewPagerActivity, when I am adding my fragments to a list:
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MainActivity.newInstance());
//fList.add(MainActivity.newInstance("Fragment 1"));
//fList.add(MyFragment.newInstance("Fragment 2"));
//fList.add(MyFragment.newInstance("Fragment 3"));
return fList;
}
}
I am getting an error at the line:
fList.add(MainActivity.newInstance());
Which is my ListFragment class (I know MainActivity throws it off but it is my ListFragment class). My listfragment class:
public class MainActivity extends ListFragment {
private List<ListViewItem> mItems;
public static MainActivity newInstance()
{
MainActivity f = new MainActivity();
Bundle bdl = new Bundle(1);
f.setArguments(bdl);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
mItems = new ArrayList<ListViewItem>();
Resources resources = getResources();
setListAdapter(new ListViewAdapter(getActivity(), mItems));
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
}
Basically, it is giving me an error because I am passing in newInstance of ListFragment but the List type is Fragments. I didn't think there should be a problem because ListFragment is a subclass of Fragment.
Error: add(android.support.v4.app.Fragment) in list cannot be applied to /MainActivity
This is why I am not sure if I should use a fragment+listview to overcome this error.
Maybe your Fragment is from support library but the ViewPager is expecting the standard Fragment