首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ChipGroup安卓系统上设置ViewPager?

如何在ChipGroup安卓系统上设置ViewPager?
EN

Stack Overflow用户
提问于 2020-02-03 14:30:54
回答 1查看 441关注 0票数 1

我有一个ChipGroup,里面有5个芯片。我有一个有5页的视图分页器。对于我选择的芯片,应该加载相应的页面(片段)。如何在安卓系统中连接ViewPager和ChipGroup?

EN

回答 1

Stack Overflow用户

发布于 2020-02-12 14:04:14

app:singleSelection="true"设置为您的Chip Group XML参考this并像这样设置ViewPager

代码语言:javascript
复制
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);
    }

然后使用addChipsToChipGroup(categoryList);将芯片动态添加到您的芯片组

代码语言:javascript
复制
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);
            }
        }
    }

最后在您的芯片组上设置选中的已更改侦听器

代码语言:javascript
复制
mChipGroup.setOnCheckedChangeListener((group, checkedId) ->
                mViewPagerGetStarted.setCurrentItem(checkedId,true));

style.xml:

代码语言:javascript
复制
 <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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60034125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档