As @sat answer, good approach for getting color is
ResourcesCompat.getColor(getResources(), R.color.your_color, null);
or use below way when you don't have access to getResources()
method.
Context context = getContext(); // like Dialog class
ResourcesCompat.getColor(context.getResources(), R.color.your_color, null);
public void someMethod(){
...
ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
}
It is most simple to use anywhere in your app! Even in Util class or any class where you don't have Context or getResource()
When you don't have Context
access, like a method in your Util
class.
Assume below method without Context.
public void someMethod(){
...
// can't use getResource() without Context.
}
Now you will pass Context
as a parameter in this method and use getResources().
public void someMethod(Context context){
...
context.getResources...
}
So here is a Bonus unique solution by which you can access resources from anywhere like Util class
.
Add Resources
to your Application
class or Create one if does not exist.
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static App mInstance;
private static Resources res;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
res = getResources();
}
public static App getInstance() {
return mInstance;
}
public static Resources getResourses() {
return res;
}
}
Add name field to your manifest.xml
<application
tag. (If not added already)
<application
android:name=".App"
...
>
...
</application>
Now you are good to go. Use ResourcesCompat.getColor(App.getRes(), R.color.your_color, null);
anywhere in app.