【问题标题】:Android: Material Design Chip - show close icon only when selectedAndroid:Material Design Chip - 仅在选择时显示关闭图标
【发布时间】:2022-01-05 13:48:39
【问题描述】:

我正在使用 Material Chip,我只想在选择 Chip 时显示 closeIcon

我怎样才能实现这种行为?我可以做一些绑定等,但我更喜欢一些更简单的解决方案。

<com.google.android.material.chip.ChipGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipSpacing="8dp"
            app:singleLine="true"
            app:singleSelection="false">

            <com.google.android.material.chip.Chip
                android:id="@+id/chip_1"
                style="@style/MyChipStyle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:closeIcon="@drawable/ic_cross_white_24dp"
                app:closeIconEnabled="true"
                app:checkedIconEnabled="false"
                android:checkable="true"
                android:text="Example text" />

        </com.google.android.material.chip.ChipGroup>

【问题讨论】:

    标签: android android-layout material-design material-components-android


    【解决方案1】:

    您需要添加代码来检查是否选择了芯片。

    试试下面的代码来检查:

    private void chipCloseBtnVisi(){
        if(chip_1.isChecked()){
            // If Chip is selected(checked) then show close icon
            chip_1.setCloseIconVisible(true);
        }else{
            // If Chip is not selected(checked) then hide close icon
            chip_1.setCloseIconVisible(false);
        }
    }
    

    要改变校验状态,需要在芯片上添加setOnCheckedChangeListener

    chip_1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    chipCloseBtnVisi();
                }
            });
    

    【讨论】:

    • 感谢您的回复。我知道它可以使用代码或一些绑定来完成。我只是好奇是否有任何更简单的方法可以在 xml 布局本身中设置它而无需任何额外的逻辑。
    猜你喜欢
    • 2020-03-25
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2022-01-10
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多