Ber*_*y92 8 resources android themes android-package-managers
我知道有一种方法可以通过在styles.xml中定义来设置主题并使用它
setTheme(android.R.style.MyTheme);
Run Code Online (Sandbox Code Playgroud)
但是,我想从我开发的另一个应用程序中获取主题.我知道资源名称,实际上我能够使用此代码块获取主题ID;
Resources res = getPackageManager().getResourcesForApplication("com.example.theme");
int resThemeId = res.getIdentifier("my_theme","style","com.example.theme");
Run Code Online (Sandbox Code Playgroud)
当我调试时,我看到resThemeId不为零.
然后,我需要最后的命令来设置这个主题.在super.onCreate()函数之前,我尝试实现此方法,但它似乎无法正常工作
setTheme(resThemeId);
Run Code Online (Sandbox Code Playgroud)
但不是这样,如果我写下面的陈述,我工作正常
setTheme(android.R.style.Theme_Holo_Light);
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么做才能使用来自不同包资源的主题呢?
那么,我应该怎么做才能使用不同包资源中的主题呢?
由于多种原因,您不应该这样做。我编写了一个简单的项目,表明只要包包含您的活动使用的资源,这确实是可能的。
请参阅: 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这只是为了表明这是可能的。我再次建议您避免这种情况。
| 归档时间: |
|
| 查看次数: |
1223 次 |
| 最近记录: |