Cannot add text color state list to Material Chip
The issue is here:
val chip = Chip(context, null, R.style.Widget_MaterialComponents_Chip_Choice)
In this way you aren't using the Widget.MaterialComponents.Chip.Choice
style since you can't use the constructor val chip = Chip(context, null, R.style.xxxx)
to assign a style because the 3rd parameter isn't the style but the attribute in the theme as R.attr.chipStyle
.
For more details to change the Chip style programmatically check also this answer.
In your code you are using the default style for a Chip
the Widget.MaterialComponents.Chip.Action
which provides:
<item name="android:checkable">false</item>
It explains why your Chip
is not checkable.
The method chip.setTextColor
is correct and works with a selector (but use the selector as described by Ben.P in the other answer).
As you pointed out if you use it in the layout.xml it works since in this case the style declared in the layout is correct (Widget.MaterialComponents.Chip.Choice
).
Is there a way to stay on the same Chip when I press it?
In other words, is there a property that keeps the checked check in its state even if it is still
selected?
Use Chip Choice then add the chips inside ChipGroup.
Add this line to your ChipGroup
<com.google.android.material.chip.ChipGroup
app:singleSelection="true"
app:selectionRequired="true"
app:checkedChip="@id/..."
..>
Then in your Chip
<android.support.design.chip.Chip
android:id="@+id/chip1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkable="true"
android:checked="true"
app:chipBackgroundColor="@color/bg_chip_state_list"
app:chipText="Test1" />
<android.support.design.chip.Chip
android:id="@+id/chip2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkable="true"
app:chipBackgroundColor="@color/bg_chip_state_list"
app:chipText="Test2" />
The key is the ChipGroup that has required selection
Related Topics
How to Create Ripple Effect in Simple Layout
Fragment View in Viewpager Is Not Restored When Resuming
Failed to Execute Tools\Android.Bat: Solution
Onlistitemclick Is Not Working for Listview
Android Studio - Error:Program Type Already Present
Android Custom Url to Open App Like in iOS
Does Android Webview Browsers Support HTML5 Features
Android: Listview.Getscrolly() - Does It Work
Display the App Icon If the Contact Is Associated with the Application in Phone Address Book
Failed to Find Style 'Mapviewstyle' in Current Theme
How to Know the Calling Activity in Android
Is Fcm (Firebase Cloud Messaging) Token for One Device or for One Account
Bordercolor Not Picking The Lineargradient Color on Android
App Crashes on Startup Due to Java.Lang.Illegalargumentexception: Column '_Id' Does Not Exist
How to Read All The Coming Notifications in Android
How to Apply Primary Key on the Text Fields in Android Database