android - 以编程方式获取应用于 Activity 的主题值

标签 android android-activity android-theme android-styles

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

一般我们都是通过使用来设置主题

setTheme(android.R.style.Theme_Light);

这里我们指定了样式,这样我们就能够以编程方式获得准确应用于 Activity 的特定样式类型。

谢谢

最佳答案

Context 类有一个很好的方法,叫做 getThemeResId,但是它是私有(private)的,因此您需要使用反射。

这是一个例子:

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

关于android - 以编程方式获取应用于 Activity 的主题值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26301345/

相关文章:

Android如何重新启动我的应用程序以前运行的 Activity

android - 为什么我的默认警报对话框按钮文本是白色的?

android - 无法使用 Theme.Dialog 启动 Activity

android - 为什么 AVD Manager 中没有 "Nexus 5"?改用什么选项?

android - 如何在设备的相机 View 中显示位置标记

android - 为什么单击后退按钮时,许多Android应用程序中的闪光灯屏幕没有关闭?

android - Android 中的 Activity 识别不起作用

android - 如何在 Android 中以编程方式替换 View ?

android - WakefulBroadcastReceiver 中 IntentService 中的 BroadcastReceiver 并不总是有效

android - 在运行时在 android 中更改 Activity 的布局