android - 我怎样才能在xml中做到这一点?
问题描述
当用户单击文本时,必须更改文本颜色及其背景颜色!
注意有两个recyclerView。
我尝试使用带有 (android:state_focused="true") 的选择器,但是当我单击第二个 recyclerView 中的文本时,焦点从第一个中消失了!
该应用程序是阿拉伯语
解决方案
为此,您可以使用 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));
我希望我能帮助你
推荐阅读
- mysql - 在表中的所有列中使用空值更新空白值
- git - Git Tfs 克隆仅显示主分支上的提交
- python - 根据元素列表在 dynamo db 中获取结果
- javascript - 使用 javascript 为 url 添加图像扩展名
- python - 是否有任何工具可以检查具有 Python 依赖项的控制器的测试覆盖率?
- javascript - Cordova 后退按钮 动作监听器不工作
- type-theory - 精益传递类型作为参数
- node.js - 如何使用电子制作以 sqlite3 作为数据库的 ionic4 应用程序的 exe 文件?
- javascript - 请帮我!此 Ui Allert 有效,但不完全
- haskell - 使用 graphviz 可视化 Haskell 数据树