android-fragments 根据所选主题更改MPPieChart图例文本颜色

9fkzdhlc  于 2022-11-14  发布在  Android
关注(0)|答案(3)|浏览(124)

场景:我制作了一个应用程序,它可以通过编程在亮和暗模式之间切换主题。它基于片段,我通过XML调用“?attr/mytextcolor”来设置每个视图,“?attr/mytextcolor”调用我的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>
 .......

现在我插入了一个MPPieChart,我想根据选择的主题改变文本颜色。我想这就像

l.setTextColor(R.attr.mytextcolor);

但是它没有做出任何改变....我做错了什么?或者,我想调用getTheme来改变它,并找到应用了哪个主题...我找到了一些关于反射的东西,但我不知道如何应用到片段

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;

有人能指出我代码中的错误吗?或者更好的解决方案?
提前感谢Alex

q3qa4bjr

q3qa4bjr1#

最后,我用这种方式解决我的问题:

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

fdbelqdn2#

我的解决方案:正在发送到图表类“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)}
    }
kb5ga3dv

kb5ga3dv3#

解决方案很简单,在灯光和夜晚主题中配置您想要的颜色,然后设置它
如果您想了解更多信息,请点击这里。

相关问题