我正在查看有关如何使用 TabLayout 的指南。这就是他们显示附加 PagerAdapter 类的方式。
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity.this));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
但是,他们的 TabLayout 在 Activity 中,而我的在 Fragment 中。我无法根据我的用例调整他们的代码,因为我不完全理解活动和片段之间的实际差异。现在,当我尝试在标签之间滑动时,什么也没有发生。这是我的代码:
public class CandidateListFragment extends Fragment {
public static final String TAG = "candidates";
@InjectView(R.id.tabLayout) TabLayout tabLayout;
public CandidateListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_candidatelist, container, false);
initInstances(v);
return v;
}
private void initInstances(View v){
//TODO: Change to support below API level 21
getActivity().findViewById(R.id.toolbar_actionbar).setElevation(R.dimen.toolbar_candidatelist_elevation);
ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabsFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
getActivity()));
ButterKnife.inject(this, v);
tabLayout.setupWithViewPager(viewPager);
}
@Override public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}