如何以编程方式创建Android主题样式? [英] How to programmatically create an Android theme style?

查看:115
本文介绍了如何以编程方式创建Android主题样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于通过XML创建或自定义Android主题样式的文档和教程,但是还没有找到在代码中创建它的方法.关于如何在代码而不是xml中创建样式的任何想法?

There are lots of docs and tutorials on creating or customising an Android theme style via XML, but have not been able to find a way to create it in code. Any ideas on how to create the style in code rather than xml?

这是示例XML,需要通过代码以编程方式创建此代码:

This is the example XML, need to create this programmatically in code:

<resources>
  <style name="AppTheme" parent="android:Theme.Material">
    <item name="android:colorPrimary">@color/primary</item>
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
    <item name="android:colorAccent">@color/accent</item>
  </style>
</resources>

推荐答案

简短答案:按照编程方式,它的不可能 创建主题和设置为没有主题资源ID的应用程序主题(即使我们实现了创建Theme对象的目的).

short answer: Its not possible as programmatically create a theme & set as application theme ( even if we achieved to create a Theme object) without a theme resource id.

详细信息:

当您调用setTheme时,该函数会影响ContextWrapper的方法, 最后使用资源ID指针调用AssetManagerAssetManager类保留了应用程序主题的应用方法,即JNI调用

when you call setTheme the function ineffect a method of ContextWrapper, which at the end calls AssetManager with resource id pointer, AssetManager class holds the method for applying application theme, which is JNI call

native static final void applyThemeStyle(long theme, int res, boolean force);

如上所述,我们只能传递资源ID来应用主题样式.但是可能的选项是

As above we can only pass a resource id to apply the themestyle. But possible options are

  1. 尽管仅限于Window类特征常量.我们可以用 setFeatureDrawable &设置一些可绘制对象的特征常量 例如FEATURE_ACTION_BARFEATURE_CONTEXT_MENU等.
  2. 在活动中使用 setTheme 函数,我们可以从样式资源中设置主题,这将解决AjaySharma& Nathan
  1. Though its limited to Window class feature constants. We can use setFeatureDrawable & feature constants to set some drawables like, FEATURE_ACTION_BAR, FEATURE_CONTEXT_MENU etc..
  2. Using setTheme function from activity, we can set the theme from style resource, that will solve the problem mentioned in comments by AjaySharma & Nathan

这篇关于如何以编程方式创建Android主题样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆