Get the Theme value applied for an activity programmatically

前端 未结 1 2055
我在风中等你
我在风中等你 2020-12-09 13:21

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_Li         


        
相关标签:
1条回答
  • 2020-12-09 13:55

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

    Here's an example:

    @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;
    }
    
    0 讨论(0)
提交回复
热议问题