关于MagicIndicator控件单独使用总结

问题描述,在使用MagicIndicator控件的时候,遇到一个一问题如果将MagicIndicator与ViewPager解绑的话应该怎么做?

解决方法:

 MagicIndicator magicIndicator = (MagicIndicator) findViewById(R.id.magic_indicator);
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return datas.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(getResources().getColor(R.color.color_gray));
                simplePagerTitleView.setSelectedColor(getResources().getColor(R.color.red_text_item1));
                simplePagerTitleView.setText(datas.get(index));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //原来的viewpager
                      //  vp.setCurrentItem(index);
                        //改动之后的代码
                        magicIndicator.onPageSelected(index);
                        magicIndicator.onPageScrolled(index, 0.0F, 0);

                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(getResources().getColor(R.color.red_text_item1));
                return linePagerIndicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, vp);

在这里magicIndicator.onPageScrolled(index, 0.0F, 0);是一定要添加的 所以你会发现其实在bind里面只有ViewPager能触发onPageScrolled才会正常

 

public class ViewPagerHelper {
    public ViewPagerHelper() {
    }

    public static void bind(final MagicIndicator magicIndicator, ViewPager viewPager) {
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                magicIndicator.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            public void onPageSelected(int position) {
                magicIndicator.onPageSelected(position);
            }

            public void onPageScrollStateChanged(int state) {
                magicIndicator.onPageScrollStateChanged(state);
            }
        });
    }
}
所以你会发现ViewPage在红色方法执行后才能正常的改变magicindactor,不信的话自己可以创建一个没有界面显示的ViewPager,是存在无法正常切换指示器的

初略标记下,防止第二次出错

你可能感兴趣的:(关于MagicIndicator控件单独使用总结)