首页 > 解决方案 > 我怎样才能在xml中做到这一点?

问题描述

当用户单击文本时,必须更改文本颜色及其背景颜色!

注意有两个recyclerView。

我尝试使用带有 (android:state_focused="true") 的选择器,但是当我单击第二个 recyclerView 中的文本时,焦点从第一个中消失了!

该应用程序是阿拉伯语

截屏

标签: androidandroid-studioandroid-layout

解决方案


为此,您可以使用 ChipGroup 和 Chip ( https://material.io/develop/android/components/chip/ ) 并在选择芯片时更改颜色

对于 ChipGroup 并在 XML 中添加 Chip :

         <com.google.android.material.chip.ChipGroup
                    android:id="@+id/chipGroupOne"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="4dp"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="4dp"
                    android:layout_marginEnd="4dp"
                    android:layout_marginRight="4dp"
                    android:layout_marginBottom="4dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent">

                      <com.google.android.material.chip.Chip
                        android:id="@+id/chip"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />

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

在代码中,像这样在组中添加芯片:

                ChipGroup chipGroup = view.findViewById(R.id.chipGroupOne);
                Chip chip = new Chip(getContext());
                chip.setId(id);
                chip.setText("text");
                chip.setCheckable(true);
                chipGroup.addView(chip);

要更改您想要的颜色,您需要使用自定义样式更改芯片样式属性,例如

样式.xml

<style name="CustomChip" parent="@style/Widget.MaterialComponents.Chip.Choice">
    <item name="chipBackgroundColor">@color/chip_state</item>
    <item name="android:textColor">@color/text_color_chip</item>
</style>

text_color_chip.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
       android:color="@color/primaryColorCheck" />
    <item android:state_checked="false"
       android:color="@color/primaryColorUncheck" />
</selector>

芯片状态.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:color="@color/colorSecondaryLight" android:state_checked="true" />
   <item android:color="@color/colorPrimaryDark" />
</selector>

并在 XML 中应用类似的样式,并将此属性添加到芯片中

    style="@style/CustomChip"

如果您想以编程方式将样式应用于芯片,则需要将包含样式的新 ChipDrawable 应用于芯片,如下所示:

芯片.xml

<chip xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

   style="@style/CustomChip"
/>

并在代码中这样应用

                    chip.setChipDrawable(ChipDrawable.createFromResource(getContext(), R.xml.chip));

我希望我能帮助你


推荐阅读