在片段中实现滑动标签

时间:2015-06-27 17:44:38

标签: android android-fragments android-tablayout

我正在查看有关如何使用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中,而我的TabLayout位于片段中。我无法将他们的代码调整到我的用例,因为我不完全理解活动和片段之间的实际差异。现在,当我尝试在标签之间滑动时,没有任何反应。这是我的代码:

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);
}

1 个答案:

答案 0 :(得分:3)

我想通了! 我的片段设置为RelativeLayout而不是LinearLayout的xml布局文件,所以我的ViewPager不在屏幕上,这意味着我无法刷卡。这是我遇到的简单错误