-2

I'm trying to change the button color using this line of code: button.setTextColor(R.color.erik_secundario)

But it doesn't work. So I also read about using that: getResources().getColor(R.color.example_color)

And the problem is that i don't know where i need to implement that code to solve the problem.

Thanks!

  • Sorry, not the button color but the button text color. – Farquaad-_- Dec 05 '19 at 21:44
  • `getResources().getColor()` returns the value you want to pass to the `setTextColor()` call, so either just put `getResources().getColor(R.color.erik_secundario)` in `setTextColor()` instead, or assign it to an `int` variable first, and pass that to `setTextColor()`. – Mike M. Dec 05 '19 at 21:50
  • Thanks, i think it's working, but now appears a message that says "getcolor() deprecated in Java". Is there any problem if i'm using kotlin? – Farquaad-_- Dec 05 '19 at 21:54
  • No, it's not that you're using it with Kotlin. Have a look at [this post](https://stackoverflow.com/q/31590714). – Mike M. Dec 05 '19 at 21:57
  • Just saw it, but i don't know what means "context", is there any other option to change text color? – Farquaad-_- Dec 05 '19 at 22:03
  • Your `Activity` is a `Context`. You can just pass `this` or `YourActivity.this`, as needed. – Mike M. Dec 05 '19 at 22:07
  • Okey, I arrived that point: `button.setTextColor(ContextCompat.getColor(getActivity(), R.color.erik_secundario)`. Now there's another message that calls me to fill `getActivity()`. What should i write inside? – Farquaad-_- Dec 05 '19 at 22:15
  • Why did you write `getActivity()`? – Mike M. Dec 05 '19 at 22:19
  • I saw it on a post, its useless? – Farquaad-_- Dec 05 '19 at 22:29
  • If you're in an `Activity` class, you don't use `getActivity()`. You use `this`, or `YourActivityName.this`. – Mike M. Dec 05 '19 at 23:03

1 Answers1

1

when you choose getResources().getColor(R.color.example_color), it will show line through which means deprecated. So you have to use ContextCompat.getColor(context,R.color.white). for context parameter, if you are using it in Activity, use this@YourActivity and in Fragment, use contextor activity. hope it will help your problem.

Win Phyoe Thu
  • 213
  • 2
  • 9