我知道有一种方法可以通过在 styles.xml 中定义并像这样使用它来设置主题
setTheme(android.R.style.MyTheme);
但是,我想从我开发的另一个应用程序中获取主题。我知道资源名称,实际上我可以使用此代码块获取主题 id;
Resources res = getPackageManager().getResourcesForApplication("com.example.theme");
int resThemeId = res.getIdentifier("my_theme","style","com.example.theme");
当我调试时,我发现 resThemeId 不为零。
然后,我需要最后的命令来设置这个主题。在 super.onCreate() 函数之前,我尝试实现此方法,但似乎不起作用
setTheme(resThemeId);
但如果我写下面的语句,而不是这个,我工作得很好
setTheme(android.R.style.Theme_Holo_Light);
那么,我应该怎么做才能使用不同包资源中的主题呢?
那么,我应该怎么做才能使用不同包资源中的主题呢?
由于多种原因,您不应该这样做。我编写了一个简单的项目,表明只要包包含您的活动使用的资源,这确实是可能的。
See: https://github.com/jaredrummler/SO-41872033 https://github.com/jaredrummler/SO-41872033
基本上,您需要从活动返回包的资源:
public class MainActivity extends AppCompatActivity {
Resources resources;
@Override protected void onCreate(Bundle savedInstanceState) {
int themeResId = getResources().getIdentifier("AppTheme", "style", "com.example.theme");
if (themeResId != 0) {
setTheme(themeResId);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override public Resources getResources() {
if (resources == null) {
try {
resources = getPackageManager().getResourcesForApplication("com.example.theme");
} catch (PackageManager.NameNotFoundException e) {
resources = super.getResources();
}
}
return resources;
}
}
这只是为了表明这是可能的。我再次建议您避免这种情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)