Android - Activity to use multiple themes via ContextThemeWrapper

    Android's Manifest specifications supports theme either at the application level or at the activity level but what if we want different UI elements within the same activity to be based on different themes? Android provides an utility ContextThemeWrapper for this purpose.

        ContextThemeWrapper newThemeContext = new ContextThemeWrapper(this /*activityContext*/, android.R.style.Theme_Holo);

        LayoutInflater inflater = (LayoutInflater) newThemeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View newView = inflater.inflate(R.layout.activity_sub_main, null);

   ContextThemeWrapper is an specific extension of a ContextWrapper providing theme override functionality. An instance of this overrides the wrapped context's theme and uses the new theme. Its important to invoke getSystemService() on the new context rather than the wrapped context as the overridden version actually clones the context.

    @Override public Object getSystemService(String name) {
        if (LAYOUT_INFLATER_SERVICE.equals(name)) {
            if (mInflater == null) {
                mInflater = LayoutInflater.from(mBase).cloneInContext(this);
            }
            return mInflater;
        }
        return mBase.getSystemService(name);
    }

No comments: