得到应用主题价值的活动编程价值、主题

2023-09-07 09:50:10 作者:你是年少的欢喜

我想知道哪些主题是在应用程序申请了一个活动。

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.

感谢

推荐答案

上下文类有一个很好的方法 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;
}