【问题标题】:Get the Theme value applied for an activity programmatically以编程方式获取应用到活动的主题值
【发布时间】:2014-10-10 14:06:00
【问题描述】:

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

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

setTheme(android.R.style.Theme_Light);

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

谢谢

【问题讨论】:

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


    【解决方案1】:

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

    这是一个例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2015-01-14
      • 2019-08-17
      • 2016-06-20
      相关资源
      最近更新 更多