【问题标题】:Dynamically find the theme name in Android application在 Android 应用中动态查找主题名称
【发布时间】:2014-01-29 12:46:30
【问题描述】:

我有一个平板电脑应用程序,我正在重新命名,因此有多个主题,具体取决于用户类型。

我想找到当前正在应用的主题的名称,然后我可以根据该主题进行一些后端功能更改。

我必须动态设置一些图像资源,只要我传入正确的主题资源(R.style.redtheme)就可以了,但我想动态设置。

TypedArray a = getTheme().obtainStyledAttributes(R.style.redtheme, new int[] {aTabResource.mDrawableAttrId});

为了进行样式设置,我创建了自定义属性,然后在样式中覆盖它们。

如果没有简单的方法来获取主题,我只会保存一个首选项。

【问题讨论】:

    标签: android android-theme


    【解决方案1】:

    包管理器可以访问相当多的元数据。

    可以这样访问:

    int theme = 0; //0==not set
    try 
    {
        String packageName = getClass().getPackage().getName();
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_META_DATA);
        theme = packageInfo.applicationInfo.theme;
    }
    catch (Exception e) 
    { 
        e.printStackTrace();
    }
    

    运行后,主题将拥有样式资源。

    【讨论】:

    • 这个有点问题,它得到了错误的包名。如果将第一行更改为 String packageName = mContext.getPackageName(); 则有效,其中 mContext 是 Activity 的上下文,即 private void createActivity(Bundle savedInstanceState){ setContentView(R.layout.welcome_layout); mContext = this;
    • getClass().getPackage() 不是我们要找的包。应该使用 mContext.getPackageName()
    • getClass().getPackage() 返回应用程序的包。 mContext.getPackageName() 返回当前文件对应的包名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多