下面列出了android.content.Context#setTheme ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Called in onCreate() to check the UI Mode (day or night)
* and set the theme colors accordingly.
*
* @param context {@link NavigationView} where the theme will be set
* @param attrs holding custom styles if any are set
*/
static void setTheme(Context context, AttributeSet attrs) {
boolean nightModeEnabled = isNightModeEnabled(context);
updatePreferencesDarkEnabled(context, nightModeEnabled);
if (shouldSetThemeFromPreferences(context)) {
int prefLightTheme = retrieveThemeResIdFromPreferences(context, NavigationConstants.NAVIGATION_VIEW_LIGHT_THEME);
int prefDarkTheme = retrieveThemeResIdFromPreferences(context, NavigationConstants.NAVIGATION_VIEW_DARK_THEME);
prefLightTheme = prefLightTheme == 0 ? R.style.NavigationViewLight : prefLightTheme;
prefDarkTheme = prefLightTheme == 0 ? R.style.NavigationViewDark : prefDarkTheme;
context.setTheme(nightModeEnabled ? prefDarkTheme : prefLightTheme);
return;
}
TypedArray styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.NavigationView);
int lightTheme = styledAttributes.getResourceId(R.styleable.NavigationView_navigationLightTheme,
R.style.NavigationViewLight);
int darkTheme = styledAttributes.getResourceId(R.styleable.NavigationView_navigationDarkTheme,
R.style.NavigationViewDark);
styledAttributes.recycle();
context.setTheme(nightModeEnabled ? darkTheme : lightTheme);
}
public static void setTheme(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean dark = prefs.getBoolean("dark_theme", false);
String theme = prefs.getString("theme", "teal");
if (theme.equals("teal"))
context.setTheme(dark ? R.style.AppThemeTealDark : R.style.AppThemeTeal);
else if (theme.equals("blue"))
context.setTheme(dark ? R.style.AppThemeBlueDark : R.style.AppThemeBlue);
else if (theme.equals("purple"))
context.setTheme(dark ? R.style.AppThemePurpleDark : R.style.AppThemePurple);
else if (theme.equals("amber"))
context.setTheme(dark ? R.style.AppThemeAmberDark : R.style.AppThemeAmber);
else if (theme.equals("orange"))
context.setTheme(dark ? R.style.AppThemeOrangeDark : R.style.AppThemeOrange);
else if (theme.equals("green"))
context.setTheme(dark ? R.style.AppThemeGreenDark : R.style.AppThemeGreen);
if (context instanceof Activity && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
setTaskColor(context);
}
public void apply(@NonNull Context context) {
final boolean dark = preferences.getBoolean(KEY_THEME_DARK, false);
// we have only 2 themes and Light one is default
final int theme;
if (dark) {
theme = R.style.AppThemeDark;
} else {
theme = R.style.AppThemeLight;
}
final Context appContext = context.getApplicationContext();
if (appContext != context) {
appContext.setTheme(theme);
}
context.setTheme(theme);
}
public static Context getNewPluginContext(Context pluginContext) {
if (pluginContext != null) {
pluginContext = PluginCreator.createPluginApplicationContext(((PluginContextTheme) pluginContext).getPluginDescriptor(),
mApplication, pluginContext.getResources(),
(DexClassLoader) pluginContext.getClassLoader());
pluginContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
}
return pluginContext;
}
public static void setTheme(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean dark = prefs.getBoolean("dark_theme", false);
String theme = prefs.getString("theme", "teal");
if (theme.equals("teal"))
context.setTheme(dark ? R.style.AppThemeTealDark : R.style.AppThemeTeal);
else if (theme.equals("blue"))
context.setTheme(dark ? R.style.AppThemeBlueDark : R.style.AppThemeBlue);
else if (theme.equals("purple"))
context.setTheme(dark ? R.style.AppThemePurpleDark : R.style.AppThemePurple);
else if (theme.equals("amber"))
context.setTheme(dark ? R.style.AppThemeAmberDark : R.style.AppThemeAmber);
else if (theme.equals("orange"))
context.setTheme(dark ? R.style.AppThemeOrangeDark : R.style.AppThemeOrange);
else if (theme.equals("green"))
context.setTheme(dark ? R.style.AppThemeGreenDark : R.style.AppThemeGreen);
if (dark) {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO);
}
if (context instanceof Activity && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
setTaskColor(context);
}
static void setActivityTheme(Context context) {
SharedPreferences prefManager = PreferenceManager.getDefaultSharedPreferences(context);
boolean darkTheme = prefManager.getBoolean(context.getString(R.string.settings_dark_key), Boolean.getBoolean(context.getString(R.string.settings_dark_default)));
if (darkTheme) {
context.setTheme(R.style.AppThemeDark);
} else {
context.setTheme(R.style.AppTheme);
}
}
/**
* 根据当前插件的默认Context, 为当前插件的组件创建一个单独的context
*
* @param pluginContext
* @param base 由系统创建的Context。 其实际类型应该是ContextImpl
* @return
*/
/*package*/ static Context getNewPluginComponentContext(Context pluginContext, Context base) {
Context newContext = null;
if (pluginContext != null) {
newContext = PluginCreator.createPluginContext(((PluginContextTheme) pluginContext).getPluginDescriptor(),
base, pluginContext.getResources(),
(DexClassLoader) pluginContext.getClassLoader());
newContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
}
return newContext;
}
static void setTheme() {
//Avoid this exception:
//java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
final Context context = instrumentation.getTargetContext();
context.setTheme(R.style.AppTheme);
}
public static Context getNewPluginApplicationContext(Class clazz) {
Context defaultContext = getDefaultPluginContext(clazz);
Context newContext = null;
if (defaultContext != null) {
newContext = PluginCreator.createPluginContext(((PluginContextTheme) defaultContext).getPluginDescriptor(),
mApplication, defaultContext.getResources(),
(DexClassLoader) defaultContext.getClassLoader());
newContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
}
return newContext;
}
/**
* 构造插件信息
*
* @param
*/
static void ensurePluginInited(PluginDescriptor pluginDescriptor) {
if (pluginDescriptor != null) {
DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();
if (pluginClassLoader == null) {
PaLog.d("正在初始化插件Resources, DexClassLoader, Context, Application ");
PaLog.d("是否为独立插件", pluginDescriptor.isStandalone());
Resources pluginRes = PluginCreator.createPluginResource(mApplication, pluginDescriptor.getInstalledPath(),
pluginDescriptor.isStandalone());
pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath(),
pluginDescriptor.isStandalone());
Context pluginContext = PluginCreator
.createPluginContext(pluginDescriptor, mApplication, pluginRes, pluginClassLoader);
pluginContext.setTheme(mApplication.getApplicationContext().getApplicationInfo().theme);
pluginDescriptor.setPluginContext(pluginContext);
pluginDescriptor.setPluginClassLoader(pluginClassLoader);
//使用了openAtlasExtention之后就不需要Public.xml文件了
//checkPluginPublicXml(pluginDescriptor, pluginRes);
callPluginApplicationOnCreate(pluginDescriptor);
PaLog.d("初始化插件" + pluginDescriptor.getPackageName() + "完成");
}
}
}
@Before
public void createAndMeasureMemoryView() {
Context context = ApplicationProvider.getApplicationContext();
context.setTheme(R.style.Theme_AppCompat);
memoryView = new MemoryView(context);
int spec = MeasureSpec.makeMeasureSpec(500, MeasureSpec.EXACTLY);
memoryView.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
memoryView.measure(spec, spec);
memoryView.layout(0, 0, 500, 500);
}
/**
* Used by plugin for Theme
* 插件使用插件主题
*/
public static void setTheme(Context pluginContext, int resId) {
if (pluginContext instanceof PluginContextTheme) {
((PluginContextTheme)pluginContext).mTheme = null;
pluginContext.setTheme(resId);
}
}
/**
* Gets context and attach material theme.
*/
public Context getContextWithTheme() {
final Context context = ApplicationProvider.getApplicationContext();
context.setTheme(R.style.MSDKUIDarkTheme);
return context;
}
public static void setupTheme(Context context) {
context.setTheme(R.style.Mizuu_Theme);
}
private static void setBaseStyle(Context context, int themeId, int fontSizeStyleId) {
context.setTheme(themeId);
context.getTheme().applyStyle(fontSizeStyleId, true);
}
static void processSetTheme(Context context, boolean isDialog) {
try {
String string = getUiTheme(context);
if (string != null) {
switch (string) {
case "blue":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Blue : R.style.AppTheme_Default_Blue);
break;
case "orange":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Orange : R.style.AppTheme_Default_Orange);
break;
case "green":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Green : R.style.AppTheme_Default_Green);
break;
case "pink":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Pink : R.style.AppTheme_Default_Pink);
break;
case "yellow":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Yellow : R.style.AppTheme_Default_Yellow);
break;
case "black":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog : R.style.AppTheme_Default);
break;
case "red":
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_Red : R.style.AppTheme_Default_Red);
break;
case "white":
default:
context.setTheme(isDialog ? R.style.AppTheme_Default_Dialog_White : R.style.AppTheme_Default_White);
// if (Build.VERSION.SDK_INT >= 21) {
// context.setTheme(R.style.AppTheme_Default_Blue);
// } else {
// context.setTheme(R.style.AppTheme_Default);
// }
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Notification makeNotification(Context context, String artist, String track, long duration, boolean retentionNotif, boolean isPlaying) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
boolean prefOverlay = sharedPref.getBoolean("pref_overlay", false) && (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context));
int notificationPref = prefOverlay ? 2 : Integer.valueOf(sharedPref.getString("pref_notifications", "0"));
Intent activityIntent = new Intent(context.getApplicationContext(), MainActivity.class)
.setAction("com.geecko.QuickLyric.getLyrics")
.putExtra("retentionNotif", retentionNotif)
.putExtra("TAGS", new String[]{artist, track});
Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE")
.putExtra("artist", artist).putExtra("track", track).putExtra("duration", duration);
final Intent overlayIntent = new Intent(context.getApplicationContext(), LyricsOverlayService.class)
.setAction(LyricsOverlayService.CLICKED_FLOATING_ACTION);
PendingIntent overlayPending = PendingIntent.getService(context.getApplicationContext(), 0, overlayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent openAppPending = PendingIntent.getActivity(context.getApplicationContext(), 0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent wearablePending = PendingIntent.getBroadcast(context.getApplicationContext(), 8, wearableIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action wearableAction =
new NotificationCompat.Action.Builder(R.drawable.ic_watch,
context.getString(R.string.wearable_prompt), wearablePending)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(notificationPref == 1 && isPlaying ? TRACK_NOTIF_CHANNEL : TRACK_NOTIF_HIDDEN_CHANNEL,
context.getString(R.string.pref_notifications),
notificationPref == 1 && isPlaying ? NotificationManager.IMPORTANCE_LOW : NotificationManager.IMPORTANCE_MIN);
notificationChannel.setShowBadge(false);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context.getApplicationContext(), notificationPref == 1 && isPlaying ? TRACK_NOTIF_CHANNEL : TRACK_NOTIF_HIDDEN_CHANNEL);
NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context.getApplicationContext(), TRACK_NOTIF_HIDDEN_CHANNEL);
int[] themes = new int[]{R.style.Theme_QuickLyric, R.style.Theme_QuickLyric_Red,
R.style.Theme_QuickLyric_Purple, R.style.Theme_QuickLyric_Indigo,
R.style.Theme_QuickLyric_Green, R.style.Theme_QuickLyric_Lime,
R.style.Theme_QuickLyric_Brown, R.style.Theme_QuickLyric_Dark};
int themeNum = Integer.valueOf(sharedPref.getString("pref_theme", "0"));
context.setTheme(themes[themeNum]);
notifBuilder.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notif : R.drawable.ic_notif4)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(String.format("%s - %s", artist, track))
.setContentIntent(prefOverlay ? overlayPending : openAppPending)
.setVisibility(-1) // Notification.VISIBILITY_SECRET
.setGroup("Lyrics_Notification")
.setColor(ColorUtils.getPrimaryColor(context))
.setShowWhen(false)
.setGroupSummary(true);
wearableNotifBuilder.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notif : R.drawable.ic_notif4)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(String.format("%s - %s", artist, track))
.setContentIntent(openAppPending)
.setVisibility(-1) // Notification.VISIBILITY_SECRET
.setGroup("Lyrics_Notification")
.setOngoing(false)
.setColor(ColorUtils.getPrimaryColor(context))
.setGroupSummary(false)
.setShowWhen(false)
.extend(new NotificationCompat.WearableExtender().addAction(wearableAction));
if (notificationPref == 2) {
notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
wearableNotifBuilder.setPriority(-2);
} else
notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW
Notification notif = notifBuilder.build();
Notification wearableNotif = wearableNotifBuilder.build();
if (notificationPref == 2 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
if (notificationPref == 1)
notif.flags |= Notification.FLAG_AUTO_CANCEL;
try {
context.getPackageManager().getPackageInfo("com.google.android.wearable.app", PackageManager.GET_META_DATA);
NotificationManagerCompat.from(context).notify(8, wearableNotif); // TODO Make Android Wear app
} catch (PackageManager.NameNotFoundException ignored) {
}
return notif;
}
public void setAptoideTheme(Context activity) {
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(activity);
if(sPref.getString("theme", "light").equals("dark")){
activity.setTheme(R.style.AptoideThemeDefaultDark);
}else{
activity.setTheme(R.style.AptoideThemeDefault);
}
}
static void resetActivityContext(final Context pluginContext, final Activity activity,
final int pluginAppTheme) {
if (pluginContext == null) {
return;
}
// 重设BaseContext
HackContextThemeWrapper hackContextThemeWrapper = new HackContextThemeWrapper(activity);
hackContextThemeWrapper.setBase(null);
hackContextThemeWrapper.attachBaseContext(pluginContext);
// 由于在attach的时候Resource已经被初始化了,所以需要重置Resource
hackContextThemeWrapper.setResources(null);
CompatForSupportv7_23_2.fixResource(pluginContext, activity);
// 重设theme
if (pluginAppTheme != 0) {
hackContextThemeWrapper.setTheme(null);
activity.setTheme(pluginAppTheme);
}
// 重设theme
((PluginContextTheme)pluginContext).mTheme = null;
pluginContext.setTheme(pluginAppTheme);
Window window = activity.getWindow();
HackWindow hackWindow = new HackWindow(window);
//重设mContext
hackWindow.setContext(pluginContext);
//重设mWindowStyle
hackWindow.setWindowStyle(null);
// 重设LayoutInflater
LogUtil.v(window.getClass().getName());
//注意:这里getWindow().getClass().getName() 不一定是android.view.Window
//如miui下返回MIUI window
hackWindow.setLayoutInflater(window.getClass().getName(), LayoutInflater.from(activity));
// 如果api>=11,还要重设factory2
if (Build.VERSION.SDK_INT >= 11) {
new HackLayoutInflater(window.getLayoutInflater()).setPrivateFactory(activity);
}
}
static void resetActivityContext(final Context pluginContext, final Activity activity,
final int pluginAppTheme) {
if (pluginContext == null) {
return;
}
// 重设BaseContext
RefInvoker.setFieldObject(activity, ContextWrapper.class.getName(), android_content_ContextWrapper_mBase, null);
RefInvoker.invokeMethod(activity, ContextThemeWrapper.class.getName(), android_content_ContextThemeWrapper_attachBaseContext,
new Class[]{Context.class }, new Object[] { pluginContext });
// 由于在attach的时候Resource已经被初始化了,所以需要重置Resource
RefInvoker.setFieldObject(activity, ContextThemeWrapper.class.getName(), android_content_ContextThemeWrapper_mResources, null);
// 重设theme
if (pluginAppTheme != 0) {
RefInvoker.setFieldObject(activity, ContextThemeWrapper.class.getName(), android_content_ContextThemeWrapper_mTheme, null);
activity.setTheme(pluginAppTheme);
}
// 重设theme
((PluginContextTheme)pluginContext).mTheme = null;
pluginContext.setTheme(pluginAppTheme);
//重设mContext
RefInvoker.setFieldObject(activity.getWindow(), Window.class.getName(),
"mContext", pluginContext);
//重设mWindowStyle
RefInvoker.setFieldObject(activity.getWindow(), Window.class.getName(),
"mWindowStyle", null);
// 重设LayoutInflater
PaLog.d(activity.getWindow().getClass().getName());
RefInvoker.setFieldObject(activity.getWindow(), activity.getWindow().getClass().getName(),
"mLayoutInflater", LayoutInflater.from(pluginContext));
// 如果api>=11,还要重设factory2
if (Build.VERSION.SDK_INT >= 11) {
RefInvoker.invokeMethod(activity.getWindow().getLayoutInflater(), LayoutInflater.class.getName(),
"setPrivateFactory", new Class[]{LayoutInflater.Factory2.class}, new Object[]{activity});
}
}