0

I want to add a style to themes.xml so that the style changes when I click the button in the kotlin file. My code doesn't work normally, and an error occurs.

This is my code.

themes.xml

<style name="borderButton" parent="Widget.MaterialComponents.Button.TextButton"/>
<style name="borderlessButton" parent="Widget.MaterialComponents.Button.OutlinedButton"/>

Fragment.kt

binding.btnWon.setOnClickListener {
    binding.btnFore.setBackgroundResource(R.style.borderlessButton)
    binding.btnWon.setBackgroundResource(R.style.borderButton)
}

binding.btnFore.setOnClickListener {
    binding.btnWon.setBackgroundResource(R.style.borderlessButton)
    binding.btnFore.setBackgroundResource(R.style.borderButton)
}

The style resource used in the kotlin code is accessible, but the "android.content.res.res.Resources$NotFoundException: Resource ID #0x7f140455" occurs in that area.

How can we solve this? Please provide a solution. Thanks!

장인수
  • 15
  • 3
  • `setBackgroundResource` expects a Drawable resource, not a Style resource. – Tenfour04 Jun 20 '23 at 02:04
  • See here https://stackoverflow.com/a/2016344/506796 You can't set the style programmatically, but you can create a state list and modify its state. – Tenfour04 Jun 20 '23 at 02:07
  • Oh, and here's a library that seems to support changing the style programmatically. https://github.com/airbnb/paris – Tenfour04 Jun 20 '23 at 02:09
  • If "Paris" is applied, it seems possible to change it be changed programmatically. I don't think it's used well in a normal environment. – 장인수 Jun 20 '23 at 02:12

1 Answers1

0

You cannot set a style as a background resource directly in Kotlin or Java code. Instead, you need to set a drawable resource that uses the style as its background.

Venus
  • 453
  • 2
  • 9
  • The much higher answer rate and the verboseness suggest this has been generated by [ChatGPT_](https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned). – Peter Mortensen Jun 20 '23 at 16:40
  • I also think it is highly likely that this answer was generated by ChatGPT. – 장인수 Jun 21 '23 at 03:24