根据所选主题更改 MP 饼图图例文本颜色

Change MPPieChart Legend Text Color based on choosed theme

场景:我制作了一个应用程序,可以根据片段以编程方式在明暗 mode.It 之间切换主题,我通过 XML 调用“?attr/mytextcolor”设置每个视图称呼我的风格:

<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>
 .......

现在我插入了一个 MPPieChart,我想根据所选主题更改文本颜色。 我以为只是

l.setTextColor(R.attr.mytextcolor);

但它没有做任何改变.... 我究竟做错了什么? 或者,我想通过调用 getTheme 来更改它并找到应用了哪个主题......我找到了一些关于反射的东西,但我不知道如何应用到 f​​ragment

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;

谁能指出我代码中的错误?或者更好的解决方案?

提前致谢 亚历克斯

最后我是这样解决问题的:

//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);

我的解决方案: 发送到图表 class“requireContext()”

chartClass(linechart,requireContext())

在图表类中

        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)}
    }

解决方法很简单,在Light and Night Theme中配置你想要的颜色然后设置即可

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