2

I have a ChipGroup with 5 chips in it. And I have a view pager with 5 pages in it. For the chip I select, the corresponding page(fragment) should be loaded. How to link the ViewPager and the ChipGroup in android?

Ganesh S S
  • 571
  • 5
  • 10
  • Set the chip OnCheckedChangeListener() and change the view pager's page by selecting the chip. – Jaymin Feb 03 '20 at 06:38

1 Answers1

0

set app:singleSelection="true"to your Chip Group XML refer to this and set ViewPager like this

private void setViewPager() {
        mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        if (mViewPagerGetStarted != null) {
            mViewPagerGetStarted.setAdapter(mPagerAdapter);
            mViewPagerGetStarted.addOnPageChangeListener(this);
            mViewPagerGetStarted.setOffscreenPageLimit(4);
            mTabLayoutGetStarted.setupWithViewPager(mViewPagerGetStarted);
        }

        ArrayList<String> categoryList = new ArrayList<>();
        int numberOfFrag = mPagerAdapter.getCount();
        for (int i = 0; i < numberOfFrag; i++) {
            categoryList.add(mPagerAdapter.getPageTitle(i).toString());
        }
        addChipsToChipGroup(categoryList);
    }

Then add chips dynamically to your chip group using addChipsToChipGroup(categoryList);

private void addChipsToChipGroup(List<String> items) {
        if (items.size() >= 1) {
            for (int i = 0; i < items.size(); i++) {
                Chip chip = new Chip(mContext);
                chip.setId(i);
                ChipDrawable chipDrawable = ChipDrawable.createFromAttributes(this,
                        null,
                        0,
                        R.style.ChipTextStyle);

                chip.setCloseIconTint(Utils.ColorStateListFromIntColor(mColorPrimary));
                chip.setText(items.get(i));
                chip.setTextColor(mColorPrimary);
                chip.setChipDrawable(chipDrawable);
                chip.setChipBackgroundColor(Utils.ColorStateListFromIntColor(mWhiteColor));
                chip.setChipStrokeColor(Utils.ColorStateListFromIntColor(mColorPrimary));
                chip.setChipStrokeWidth(2f);
                mChipGroup.addView(chip);
            }
        }
    }

And finally set on checked changed listener on your chipgroup

mChipGroup.setOnCheckedChangeListener((group, checkedId) ->
                mViewPagerGetStarted.setCurrentItem(checkedId,true));

style.xml :

 <style name="ChipTextStyle" parent="Widget.MaterialComponents.Chip.Choice">
        <item name="android:textSize">13sp</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <item name="android:padding">5dp</item>
        <item name="checkedIconEnabled">false</item>
        <item name="checkedIcon">@null</item>
        <item name="closeIconTint">@color/colorPrimary</item>
    </style>
Saumya Rajan
  • 11
  • 1
  • 4