API级别24上的TabLayout

时间:2016-09-09 06:34:30

标签: android android-tablayout android-7.0-nougat

关于TabLayout的API级别24有哪些变化? tabLayout.setOnTabSelectedListener()已被弃用且tabLayout.addOnTabSelectedListener()工作正常,当您以编程方式单击选项卡时,侦听器正在运行两次。为什么呢?

我的代码。

private class TabSelectedListener implements TabLayout.OnTabSelectedListener {

    @Override
    public void onTabSelected(TabLayout.Tab tab) {

        final int tabIndex = tab.getPosition();
        if (tabIndex == sCalendarTabIndex) {
            openCalendar();
            mTabLayout.getTabAt(mBeforeSelectedTabIndex).select();
        } else {
            mBeforeSelectedTabIndex = tabIndex;
            final ViewPagerAdapter viewPagerAdapter = (ViewPagerAdapter) mViewPager
                    .getAdapter();

            final MyViewPagerFragment fragment = viewPagerAdapter
                    .getFragmentAtIndex(tabIndex);

            mViewPager.setCurrentItem(mBeforeSelectedTabIndex);
            fragment.refreshContent();
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }
}

2 个答案:

答案 0 :(得分:0)

<强> mTab​​Layout.getTabAt(mBeforeSelectedTabIndex)。选择(); 此行使您的选项卡被调用一次,默认情况下,当您单击选项卡时,将调用一次TabSelectedListener。

指示器自动设置为您选择的选项卡。您不需要手动设置指标。

<强> mTab​​Layout.getTabAt(mBeforeSelectedTabIndex)。选择(); 删除此行并检查您的监听器只会被调用一次

答案 1 :(得分:0)

我有类似的东西:

 @Bind(R.id.view_pager)
ViewPager viewPager;
@Bind(R.id.tab_layout)
TabLayout tabLayout;

 private void addFragments() {
    List<Fragment> fragments = new ArrayList<>();
    fragments.add(remoteFragment);
    fragments.add(chatFragment);
    fragments.add(epgFragment);
    MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.getTabAt(TAB_REMOTE_POSITION)
            .setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
    tabLayout.getTabAt(TAB_SOCIAL_POSITION)
            .setIcon(getDrawable(R.drawable.ic_group_white_24dp));
    tabLayout.getTabAt(TAB_EPG_POSITION)
            .setIcon(getDrawable(R.drawable.ic_epg_fragment_24dp));
}

class MyPageAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

}