我尝试用几个片段构建viewPager。
但是,当我启动应用程序时,我会遇到文本崩溃
尝试在空对象引用上调用虚方法'java.lang.Class java.lang.Object.getClass()'
我的代码如下:
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
MainFragment main;
CartFragment cart;
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
main = new MainFragment();
cart = new CartFragment();
}
// Returns total number of pages
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return main;
case 1:
return null;
case 2:
return null;
case 3:
return cart;
default:
return null;
}
}
}
答案 0 :(得分:0)
使用以下代码调用Fragments ...
@Override
public android.support.v4.app.Fragment getItem(int position) {
Fragment f = new Fragment();
switch (position) {
case 0:
f = new LogoFragment();
break;
case 1:
f = new AboutUsFragment();
break;
case 2:
f = new ServicesFragment();
break;
}
return f;
}
答案 1 :(得分:0)
这是我使用它的方式:
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<PagerFragments> mFragments;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
this.mFragments = new ArrayList<>();
}
public void addFragment(Fragment fragment,String title) {
PagerFragments t = new PagerFragments();
t.setTitle(title);
t.setFragment(fragment);
mFragments.add(t);
notifyDataSetChanged();
}
public void addFragment(Fragment fragment) {
PagerFragments t = new PagerFragments();
t.setFragment(fragment);
mFragments.add(t);
notifyDataSetChanged();
}
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
return mFragments.get(position).getFragment();
}
// This method return the titles for the Tabs in the Tab Strip
@Override
public CharSequence getPageTitle(int position) {
return mFragments.get(position).getTitle();
}
// This method return the Number of tabs for the tabs Strip
@Override
public int getCount() {
return mFragments.size();
}
}
PagerFragment.java:
import android.support.v4.app.Fragment;
public class PagerFragments {
Fragment fragment;
String title;
public Fragment getFragment() {
return fragment;
}
public void setFragment(Fragment fragment) {
this.fragment = fragment;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
然后在片段或活动中:
private ViewPagerAdapter viewPagerAdapter;
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPagerAdapter.addFragment(new RTopGainLossFragment(oneDay), "1D");
viewPagerAdapter.addFragment(new RTopGainLossFragment(oneWeek), "1W");
viewPagerAdapter.addFragment(new RTopGainLossFragment(oneMonth), "1M");
viewPagerAdapter.addFragment(new RTopGainLossFragment(oneYear), "YTD");
viewPagerAdapter.addFragment(new RTopGainLossFragment(ytd), "1Y");
viewPagerAdapter.addFragment(new RTopGainLossFragment(max), "MAX");
viewpager.setAdapter(viewPagerAdapter);
tab.setupWithViewPager(viewpager);