Подтвердить что ты не робот

Android: применять разные темы к фрагментам одного действия

Что я хочу сделать:

Я хочу, чтобы каждый фрагмент моей MainActivity использовал другую тему, так что ActionBar имеет разные фоновые цвета, в зависимости от видимого фрагмента.

Ситуация:

Я создал MainActivity, который использует Tabs + Swipe Navigation. Я добавил 7 вкладок (= 7 фрагментов). Я создал одну тему, которая должна применяться только к первому фрагменту (fragment_main_1).

Здесь Тема:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Blue" parent="android:Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/Blue.ActionBarStyle</item>
</style>

<style name="Blue.ActionBarStyle" parent="android:Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/Blue.ActionBar.TitleTextStyle</item>
    <item name="android:background">#33B5E5</item>
</style>

<style name="Blue.ActionBar.TitleTextStyle" parent="android:TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">#FFFFFF</item>
</style>
</resources>

После создания еще 6 тем можно прокручивать вкладки, в то время как ActionBar автоматически меняет свой фоновый цвет.

Что не работает:

Добавьте эти строки (которые я нашел здесь в stackoverflow) в Fragment1.java:

// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.Blue);

// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

// inflate the layout using the cloned inflater, not default inflater
return localInflater.inflate(R.layout.fragment_main_1,container, false);

Надеюсь, ты поможешь мне:) Спасибо.

4b9b3361

Ответ 1

Настройка темы в манифесте обычно используется для Activity.

Если вы хотите установить Theme for Fragment, добавьте следующий код в onCreateView() фрагмента:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

// create ContextThemeWrapper from the original Activity Context with the custom theme
final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);

// clone the inflater using the ContextThemeWrapper
LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

// inflate the layout using the cloned inflater, not default inflater
return localInflater.inflate(R.layout.yourLayout, container, false);
}

[Источник]

Ответ 2

Попробуйте LayoutInflater localInflater = inflater.from(contextThemeWrapper);.