簡體   English   中英

檢測 Android 設備主題(是深色還是淺色)

[英]Detect the Android device theme (is it dark or light)

您可以為您的應用設置主題,但我想知道是否可以找出設備使用的是哪個主題。 目前,我的應用程序使用Theme.AppCompat.Light 我想避免改變主題。

PS 我已經嘗試將其設置為Theme.DeviceDefault並使用反射訪問其 ID,但到目前為止還沒有運氣。

try {
    setTheme(android.R.style.Theme_DeviceDefault);

    Class<Context> contextClass = Context.class;
    Method getThemeMethod = contextClass.getMethod("getThemeResId");
    getThemeMethod.setAccessible(true);
    Log.d("Test", "" + getThemeMethod.invoke(this)); // Always returns 0

    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    Log.d("Test", getResources().getResourceEntryName(packageInfo.applicationInfo.theme)); // Returns 'Theme.DeviceDefault'
} catch (Exception e) {
    Log.d("Test", "exception", e);
}
int currentNightMode = getContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;  
switch (currentNightMode) {
    case Configuration.UI_MODE_NIGHT_NO:
        // Night mode is not active on device
        break;
    case Configuration.UI_MODE_NIGHT_YES:
        // Night mode is active on device
        break;
}    

這可能有助於ContextThemeWrapper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM