我正在尝试在片段中创建标签布局,但我在创建ViewPagerAdapter时遇到错误,因为它无法解析方法getFragmentManger() 我尝试使用getActivity但问题仍然存在
这是片段的代码
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
public static final String TAG = "HF";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<android.support.v4.app.Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}