几乎每个Android的应用都有一个叫AndroidManifest.xml的文件,几乎每个AndroidManifest.xml中有一个<application android:name="xxx" android:lable="xxx"></application>的element。在android的官方文档中,application是这么定义的:
<application android:allowTaskReparenting=["true" | "false"]
android:backupAgent="string"
android:debuggable=["true" | "false"]
android:description="string resource"
android:enabled=["true" | "false"]
android:hasCode=["true" | "false"]
android:hardwareAccelerated=["true" | "false"]
android:icon="drawable resource"
android:killAfterRestore=["true" | "false"]
android:largeHeap=["true" | "false"]
android:label="string resource"
android:logo="drawable resource"
android:manageSpaceActivity="string"
android:name="string"
android:permission="string"
android:persistent=["true" | "false"]
android:process="string"
android:restoreAnyVersion=["true" | "false"]
android:supportsRtl=["true" | "false"]
android:taskAffinity="string"
android:theme="resource or theme"
android:uiOptions=["none" | "splitActionBarWhenNarrow"] >
. . .
</application>
其中,android:theme是可以用在application中的。
但是,当你在application中用getTheme()时,可能会出现意想不到的问题——实际上这个theme并没有被应用到application的实例上。
在ApplicationInfo.java中,我们可以看到如下定义:
/**
* A style resource identifier (in the package's resources) of the
* default visual theme of the application. From the "theme" attribute
* or, if not set, 0.
*/
public int theme;
在PackageParser.java中,我们也可以看到:
ai.theme = sa.getResourceId(
com.android.internal.R.styleable.AndroidManifestApplication_theme, 0);
这证明theme的数据是已经被读取了的。
在Application.java中,attach context的时候,theme并没有被用上。
/* package */ final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
所以,修复很简单:
/* package */ final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
setTheme(mLoadedApk.getApplicationInfo().theme);
}
当然,如果你不能修改android系统,又想要在你的application中用这个theme,则需要在你的application的onCreate()中加入:
setTheme(getApplicationInfo().theme);