【问题标题】:How to set ViewPager with a ChipGroup android?如何使用 ChipGroup android 设置 ViewPager?
【发布时间】:2020-02-03 06:30:54
【问题描述】:

我有一个包含 5 个筹码的 ChipGroup。我有一个视图寻呼机,里面有 5 页。对于我选择的芯片,应该加载相应的页面(片段)。 android中如何链接ViewPager和ChipGroup?

【问题讨论】:

  • 设置芯片 OnCheckedChangeListener() 并通过选择芯片更改查看寻呼机的页面。

标签: android android-fragments android-viewpager android-chips


【解决方案1】:

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

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);将芯片动态添加到您的芯片组中

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);
            }
        }
    }

最后在您的芯片组上设置检查更改的侦听器

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多