其他分享
首页 > 其他分享> > android-在片段中实现滑动选项卡

android-在片段中实现滑动选项卡

作者:互联网

我正在查看有关如何使用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);
}

解决方法:

我想到了!!!
我将片段的xml布局文件设置为RelativeLayout而不是LinearLayout,因此ViewPager不在屏幕上,这意味着我无法滑动.就是我的简单错误

标签:android-tablayout,android-fragments,android
来源: https://codeday.me/bug/20191120/2041340.html