'Change MPPieChart Legend Text Color based on choosed theme

Scenario: I made an app that switches programmatically Theme between light and dark mode.It's based on fragment and I set every views via XML calling "?attr/mytextcolor" that calls my Style:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="mytextcolor">#2196F3</item> 
 .......
<style name="darktheme" parent="Theme.AppCompat.NoActionBar">
    <item name="mytextcolor">#212121</item>
 .......

now I inserted a MPPieChart and I want to change textcolor according to the theme chosen. I thought that just something like

l.setTextColor(R.attr.mytextcolor);

but It doesn't make any change.... What am I doing wrong? Alternatively, I thought to change it calling getTheme and find which theme is applied...I find something about reflection, but I don't know how to apply to fragment

int getThemeId() {
try {
    Class<?> wrapper = Context.class;
    Method method = wrapper.getMethod("getThemeResId");
    method.setAccessible(true);
    return (Integer) method.invoke(this);
} catch (Exception e) {
    e.printStackTrace();
}
return 0;

Can anyone point out mistakes in my code? Or better solutions?

Thanks in advance Alex



Solution 1:[1]

Finally, I resolve my problem in this way:

//codice per richiamare il colore in base al tema richiesto
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getContext().getTheme();
    theme.resolveAttribute(R.attr.textcolor, typedValue, true);
    @ColorInt int color = typedValue.data;
    l.setTextColor(color);

Solution 2:[2]

My solution: Sending to chart class "requireContext()"

chartClass(linechart,requireContext())

In chartClass

        var color = ContextCompat.getColor(context, R.color.black)

    when (context.resources?.configuration?.uiMode?.and(Configuration.UI_MODE_NIGHT_MASK)) {
        Configuration.UI_MODE_NIGHT_YES -> { color = ContextCompat.getColor(context, R.color.white)}
        Configuration.UI_MODE_NIGHT_NO -> {color = ContextCompat.getColor(context, R.color.black)}
        Configuration.UI_MODE_NIGHT_UNDEFINED -> {color = ContextCompat.getColor(context, R.color.black)}
    }

Solution 3:[3]

The solution is simple, configure your desired color in the Light and Night Theme then set it

mPPieChartLegend.textColor = ContextCompat.getColor(requireActivity(), R.color.yourColor)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Magobin
Solution 2 Crebain
Solution 3 Desilio do Carmo Lima Neto