以编程方式获取应用于活动的 Theme 值 [英] Get the Theme value applied for an activity programmatically

查看:28
本文介绍了以编程方式获取应用于活动的 Theme 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道应用程序中的 Activity 应用了哪个主题.

I want to know which theme is applied for an Activity in an application.

通常我们是通过使用来设置主题

Normally we are setting the theme by using

setTheme(android.R.style.Theme_Light);

这里我们指定了样式,这样我们就可以通过编程方式获得完全应用于活动的特定样式类型.

Here we are specifying style, As like this can we able to get the specific style type exactly applied for an activity programmatically.

谢谢

推荐答案

Context 类有一个很好的方法叫做 getThemeResId,但是它是私有的,因此你需要使用反射.

Context class has a nice method called getThemeResId, however it's private thus you need to use reflection.

这是一个例子:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    Log.e("TAG", "Def theme: " + R.style.AppTheme);
    Log.e("TAG", "Light theme: " + android.R.style.Theme_Light);
    Log.e("TAG", "Current theme id: " + getThemeId());

    setTheme(android.R.style.Theme_Light);
    Log.e("TAG", "Current theme id: " + getThemeId());
}

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

这篇关于以编程方式获取应用于活动的 Theme 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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