Java Code Examples for android.content.Context#setTheme()

The following examples show how to use android.content.Context#setTheme() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Themes.java    From Markwon with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: Util.java    From NetGuard with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: ThemeSwitcher.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: Util.java    From tracker-control-android with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 5
Source File: PluginThemeHelper.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/**
 * Used by plugin for Theme
 * 插件使用插件主题
 */
public static void setTheme(Context pluginContext, int resId) {
	if (pluginContext instanceof PluginContextTheme) {
		((PluginContextTheme)pluginContext).mTheme = null;
		pluginContext.setTheme(resId);
	}
}
 
Example 6
Source File: MemoryViewTest.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/**
 * 构造插件信息
 *
 * @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() + "完成");
		}
	}
}
 
Example 8
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source File: TestUtils.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
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);

}
 
Example 10
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
/**
 * 根据当前插件的默认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;
}
 
Example 11
Source File: Utils.java    From AudioAnchor with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
}
 
Example 12
Source File: PluginLoader.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: MizuuApplication.java    From Mizuu with Apache License 2.0 4 votes vote down vote up
public static void setupTheme(Context context) {
	context.setTheme(R.style.Mizuu_Theme);
}
 
Example 14
Source File: GenericThemeEntry.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private static void setBaseStyle(Context context, int themeId, int fontSizeStyleId) {
    context.setTheme(themeId);
    context.getTheme().applyStyle(fontSizeStyleId, true);
}
 
Example 15
Source File: RobolectricTest.java    From msdkui-android with Apache License 2.0 4 votes vote down vote up
/**
 * Gets context and attach material theme.
 */
public Context getContextWithTheme() {
    final Context context = ApplicationProvider.getApplicationContext();
    context.setTheme(R.style.MSDKUIDarkTheme);
    return context;
}
 
Example 16
Source File: ThemeUtils.java    From FreezeYou with Apache License 2.0 4 votes vote down vote up
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();
        }
    }
 
Example 17
Source File: NotificationUtil.java    From QuickLyric with GNU General Public License v3.0 4 votes vote down vote up
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;
}
 
Example 18
Source File: AptoideThemePicker.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
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);
        }




    }
 
Example 19
Source File: PluginInjector.java    From Android-Plugin-Framework with MIT License 4 votes vote down vote up
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);
	}
}
 
Example 20
Source File: PluginInjector.java    From PluginLoader with Apache License 2.0 4 votes vote down vote up
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});
	}
}