return inflater.inflate(R.layout.fragment_home, container, false);
在你的onCreateView
意思是你没有任何初始化代码返回一个新膨胀的主片段.
您应该返回您在开头创建的视图onCreateView
:
return v;
提供标签标题的示例PagerAdapter:
public class PagerAdapter extends FragmentPagerAdapter { private final ListmFragments = new ArrayList<>(); private final List mFragmentTitles = new ArrayList<>(); public PagerAdapter(FragmentManager fm) { super(fm); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } }
因此,您重构的onCreateView代码将类似于:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_home, container, false); final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout); final ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager); PagerAdapter adapter = new PagerAdapter(getFragmentManager()); adapter.addFragment(BlogFragment.newInstance(), "One"); adapter.addFragment(TrendingFragment.newInstance(), "Two"); viewPager.setAdapter(adapter); tabLayout.post(new Runnable() { @Override public void run() { tabLayout.setupWithViewPager(viewPager); } }); return v; }