Android set theme to fragment

Установить тему для фрагмента

Пытаюсь задать тему для фрагмента.

Установка темы в манифесте не работает:

Глядя на предыдущие блоги, кажется, что мне нужно использовать ContextThemeWrapper. Может ли кто-нибудь сослаться на закодированный пример? Я ничего не могу найти.

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

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

Фрагмент берет свою тему из Activity. Каждому фрагменту назначается тема Деятельности, в которой он существует.

Тема применяется в методе Fragment.onCreateView, где ваш код создает представления, которые на самом деле являются объектами, в которых используется тема.

В Fragment.onCreateView вы получаете параметр LayoutInflater, который расширяет представления и содержит контекст, используемый для темы, на самом деле это Activity. Итак, ваши раздутые представления используют тему Activity.

Чтобы переопределить тему, вы можете вызвать LayoutInflater.cloneInContext , который упоминает в Документах, что его можно использовать для изменения темы. Вы можете использовать здесь ContextThemeWrapper. Затем используйте клонированный надувной элемент для создания представлений фрагментов.

Для применения единого стиля я использовал только

в onCreateView() фрагменте, прежде чем раздувать корневой вид фрагмента, и это работает для меня.

Я также пытался отобразить диалоговое окно моего фрагмента с темой, отличной от его активности, и следовал этому решению . Как и некоторые люди, упомянутые в комментариях, я не заставлял его работать, и диалог продолжал отображаться с темой, указанной в манифесте. Проблема оказалась в том , что я строила диалог , используя AlertDialog.Builder в onCreateDialog способе и поэтому не делает использование onCreateView метода , как показано в ответ , что я связан с. И когда я создавал экземпляр, AlertDialog.Builder я передавал в контексте using, getActivity() когда я должен был использовать ConstextThemeWrapper вместо этого экземпляр .

Вот код моего onCreateDialog:

Изначально у меня был AlertDialog.Builder экземпляр, созданный следующим образом:

который я изменил на:

После этого изменения диалог фрагмента был показан с правильной темой. Итак, если у кого-то еще есть аналогичная проблема и он использует, AlertDialog.Builder то проверьте контекст, передаваемый строителю. Надеюсь это поможет! 🙂

Убедитесь, что вы android:minSdkVersion=»11″ установили в своем манифесте. Это могло быть причиной того, что пример Дэвида вам не подошел.

Кроме того, установите android:theme=»@android:style/Theme.Holo.Light» атрибут для тега, а НЕ для тега.

Другая возможная проблема может заключаться в способе получения контекста при использовании файла ContextThemeWrapper() . Если вы используете что-то вроде, getActivity().getApplicationContext() просто замените его на getActivity() .

Обычно Theme.Holo должен применяться к фрагментам, связанным с MainActivity.

Обратите внимание, что вы используете ContextThemeWrapper, когда хотите применить другую тему для своего фрагмента. Может помочь, если вы предоставите фрагмент кода из MainActivity, куда вы добавляете свои фрагменты.

Полезные ссылки:

Я попробовал решение, которое, по мнению Дэвида, работает, но не во всех сценариях:
1. для первого фрагмента, добавленного в стек, есть тема действия, а не та, которая определена в onCrateView, а для второго фрагмента, который я добавить в стек правильно их было применено к фрагменту.

2. Во втором фрагменте, который они отображали правильно, я сделал следующее: я принудительно закрыл приложение, очистив память, повторно открыв приложение, и когда действие было воссоздано с фрагментом, фрагмент изменил их неправильно. Activity, а не то же самое, что было установлено в onCrateView фрагмента.

Чтобы решить эту проблему, я сделал небольшое изменение и заменил аргумент контейнера из inflater.inflate нулевым.

Я не знаю, как надувной модуль использует в некоторых сценариях контекст из представления контейнера.

Обратите внимание: я использую android.support.v4.app.Fragment и android.support.v7.app.AppCompatActivity.

Я знаю, что это немного поздно, но это может помочь кому-то другому, потому что это помогло мне. Вы также можете попробовать добавить строку кода ниже внутри функции onCreatView фрагмента

Создайте класс java, а затем используйте макет, тему которого вы хотите изменить, в методе onCreate. Затем укажите его в манифесте как обычно.

Если вы просто хотите применить стиль для определенного фрагмента, просто добавьте эти строки перед вызовом onCreateView() или onAttach() фрагмента,

и если вы хотите установить прозрачную строку состояния, установите false для fitsSystemWindows свойства вашего корневого макета,

Я заставил его работать, установив тему в контексте фрагмента перед вызовом инфлятора.

Источник

Android styling: common theme attributes

In the previous article in this series on Android styling, we looked at the difference between themes and styles and how themes allow you to write more flexible styles and layouts which isolate changes:

Читайте также:  История героя для андроид

Android Styling: Themes vs Styles

The Android styling system offers a powerful way to specify your app’s visual design, but it can be easy to misuse…

Specifically we recommended using theme attributes to provide a point of indirection to resources, so that you can vary them (e.g. in dark theme). That is, if you find yourself writing a direct resource reference (or worse yet, a hardcoded value 😱) in a layout or style, consider if you should use a theme attribute instead.

But what theme attributes are available to use? This post highlights the common ones that you should know about; those that come from Material, AppCompat or the platform. This is not a complete list (for that I’d recommend browsing the attrs files linked below where they are defined) but these are the attributes that I use all the time.

Colors

Many of these colors come from the Material color system, which defines semantic names for colors that you can use throughout your app (implemented as theme attrs).

  • ?attr/colorPrimary The primary branding color for the app.
  • ?attr/colorSecondary The secondary branding color for the app, usually a bright complement to the primary branding color.
  • ?attr/colorOn[Primary, Secondary, Surface etc] A color which contrasts against the named color.
  • ?attr/color[Primary, Secondary]Variant An alternate shade of the given color.
  • ?attr/colorSurface A color for surfaces of components, such as cards, sheets, and menus.
  • ?android:attr/colorBackground The background for the screen.
  • ?attr/colorPrimarySurface switches between colorPrimary in the Light themes, colorSurface in the Dark theme.
  • ?attr/colorError A color for displaying errors.

Other handy colors:

  • ?attr/colorControlNormal The color applied to icons/controls in their normal state.
  • ?attr/colorControlActivated The color applied to icons/controls in their activated state (e.g. checked).
  • ?attr/colorControlHighlight The color applied to control highlights (e.g. ripples, list selectors).
  • ?android:attr/textColorPrimary The most prominent text color.
  • ?android:attr/textColorSecondary Secondary text color.

Dimens

  • ?attr/listPreferredItemHeight Standard (min) height for list items.
  • ?attr/actionBarSize The height of a toolbar.

Drawables

  • ?attr/selectableItemBackground A ripple/highlight for interactive items (also handy for foregrounds!!)
  • ?attr/selectableItemBackgroundBorderless An unbounded ripple.
  • ?attr/dividerVertical A drawable that may be used as a vertical divider between visual elements.
  • ?attr/dividerHorizontal A drawable that may be used as a horizontal divider between visual elements.

TextAppearances

Material defines a type scale — a discrete set of text styles that you should use throughout your app, each of which is provided as a theme attribute which can be set as a textAppearance . Check out the Material type scale generator to help generate a scale for different fonts.

  • ?attr/textAppearanceHeadline1 defaults to light 96sp text.
  • ?attr/textAppearanceHeadline2 defaults to light 60sp text.
  • ?attr/textAppearanceHeadline3 defaults to regular 48sp text.
  • ?attr/textAppearanceHeadline4 defaults to regular 34sp text.
  • ?attr/textAppearanceHeadline5 defaults to regular 24sp text.
  • ?attr/textAppearanceHeadline6 defaults to medium 20sp text.
  • ?attr/textAppearanceSubtitle1 defaults to regular 16sp text.
  • ?attr/textAppearanceSubtitle2 defaults to medium 14sp text.
  • ?attr/textAppearanceBody1 defaults to regular 16sp text.
  • ?attr/textAppearanceBody2 defaults to regular 14sp text.
  • ?attr/textAppearanceCaption defaults to regular 12sp text.
  • ?attr/textAppearanceButton defaults to medium all caps 14sp text.
  • ?attr/textAppearanceOverline defaults to regular all caps 10sp text.

Shape

Material employs a shape system which is implemented as theme attrs for small, medium and large components. Note that if you’re setting a shape appearance on a custom component, you likely want to use a MaterialShapeDrawable as it’s background which understands and implements the shaping.

  • ?attr/shapeAppearanceSmallComponent used for Buttons, Chips, Text Fields etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceMediumComponent used for Cards, Dialogs, Date Pickers etc. Defaults to rounded 4dp corners.
  • ?attr/shapeAppearanceLargeComponent used for Bottom Sheets etc. Defaults to rounded 0dp corners (i.e. square!)

Button Styles

This might seem super specific, but Material defines three types of buttons: Contained, Text and Outlined. MDC offers theme attrs that you can use to set the style of a MaterialButton :

  • ?attr/materialButtonStyle defaults to contained (or just omit the style).
  • ?attr/borderlessButtonStyle for a text style button.
  • ?attr/materialButtonOutlinedStyle for outlined style.

Floats

  • ?android:attr/disabledAlpha Default disabled alpha for widgets.
  • ?android:attr/primaryContentAlpha The alpha applied to the foreground elements.
  • ?android:attr/secondaryContentAlpha The alpha applied to secondary elements.

App vs Android namespace

You might have noticed that some attributes are referenced by
? android:attr/foo and others just by ?attr/bar . This is because some are defined by the Android platform, and as such you need the android part to reference them by their namespace (just like with view attributes in layouts: android:id ). Those without come from static libraries (i.e. AppCompat or MDC) which are compiled into your application, so don’t need the namespace (similar to how you might use app:baz in a layout). Some elements are defined both in the platform and in a library e.g. colorPrimary . In these cases, prefer the non-platform version, as this can be used on all API levels i.e. they’re duplicated in a library precisely to backport them. In these cases, I’ve listed the non-platform versions above.

prefer non-platform attributes which can be used on all API levels

More Resources

For a complete list of the theme attributes available to use, go to the source of truth:

Читайте также:  Восстановить меню настройки андроид 10

Material Design Components:

Do It Yourself

Sometimes there isn’t a theme attribute which abstracts something you’d like to vary by theme. No worries… create your own! Here’s an example from the Google I/O app which shows a list of conference sessions in two screens.

They’re largely similar but the left screen must leave space for the sticky time headers while the right screen does not. We implemented this by abstracting where to align items behind a theme attribute so that we can vary them by theme and use the same layout across two different screens:

1. Define the theme attribute in attrs.xml

2. Provide different values in different themes:

3. Use the theme attr in the single layout used on both screens (each using one of the above themes):

Question (mark) everything

Knowing what theme attributes are available, equips you to use them when writing your layouts, styles or drawables. Using theme attributes makes it much easier to support theming (like dark theme) and to write more flexible, maintainable code. For a deep dive on this, join us in our next post in this series:

Источник

Android set theme to fragment

Android Fragments Tutorial

You can divide your activity behavior and user interface into multiple components so that certain components in an activity can be reused and replaced with new components to create a flow of an activity or to perform a task. These components which are part of an activity are called Fragments.

You can build an application consisting of few activities with each activity representing a task consisting of multiple Fragments with each Fragment representing certain behavior in the flow of the task. Like Activity, Fragment has its own lifecycle and you need to define layout for each fragment.

Table of Contents

Creating Fragment Layout

First create fragment layout with UI elements defined in it. Defining fragment layout is similar to how layout is defined for activity.

Creating Fragments

Fragment can be created by extending Fragment or one of its subclasses such as DialogFragment, HeadersSupportFragment, ListFragment, PlaybackSupportFragment, PreferenceFragmentCompat, RowsSupportFragment, SearchSupportFragment, etc. If you want backward compatibility, you can create fragment using Fragment class from support library.

Next you need to implement onCreateView callback method. In this method, you can either instantiate user interface using LayoutInflater and Fragment layout xml or create Fragment user interface programmatically and you can add event listeners to Views and set configuration of Views. This method should return the view create for fragment user interface.

Adding Fragment to Activity

The important step that needs to be followed in order to use Fragments is creating activity that extends FragmentActivity or its subclass AppCompatActivity to have necessary framework to handle fragments in your activity.

You can add a Fragment to Activity by defining it in layout or by creating it programmatically. To add fragment to layout, you need to define fragment element and set name attribute to fragment class.

Another way of adding a fragment to an activity is by defining a ViewGroup in the activity layout and adding Fragment to it programmatically in your activity. To add fragment to ViewGroup, first get FragmentManager by calling getFragmentManager() or getSupportFragmentManager() if your fragment extends Fragment class from support library. Then get FragmentTransaction object and call add or replace on FragmentTransaction object passing the view group id and fragment instance.

Removing Fragment from Activity

To remove a fragment, first get Fragment object by calling findFragmentByTag method on FragmentManager passing fragment tag specified when it was added, then get FragmentTransaction object and call remove on FragmentTransaction object passing the fragment object.

Fragment Lifecycle

Similar to the activity, Fragment exists in three states: resumed state, paused state and stopped state. In resumed state, the fragment is visible in foreground activity. A fragment will be in paused state when the fragment and container activity is visible but not in the foreground because the focus is on another activity which is transparent. A fragment will be in stopped state when the fragment is not visible either because the container activity is not visible or the fragment has been removed by the activity and added to back stack. In the stopped state, fragment instance is retained by the system.

Lifecycle of the fragment is similar to the activity lifecycle with few extra callback methods to handle interaction with the activity.

When Fragment is created, onAttach(), onCreate(), onCreateView(), onViewCreated() and onActivityCreated() callback methods are called. Callback method onAttach() is called when a fragment is first attached to context. Callback method onCreateView gives the opportunity to instantiate fragment user interface. In callback method onViewCreated (), you can initialize views and apply saved sate in the case of fragment being recreated. Callback method onActivityCreated() is called after activity has been created and fragment’s view hierarchy is instantiated, it give a chance to do the final initialization.

Below is the order in which Fragment callback methods are called when fragment is created and added to an activity regardless of how it is added to the activity. Meaning same order is followed when the fragment is added to the activity by defining fragment in the activity xml or Fragment is added or replaced using FragmentTransaction.

Читайте также:  Elm327 драйвер для андроида

Callback method onStart is called when the fragment is created or every time the fragment comes to foreground. Callback method onResume is called when fragment is visible but not in foreground. These call back methods onStart and onResume are called when corresponding methods in the activity are called.

When fragment is destroyed callback methods onDestroyView(),onDestroy() and onDetach() are called. Callback method onDestroyView() is called when the fragment view is detached from fragment. Callback method onDetach() is called when the fragment is detached from the activity. Callback method onDestroy() is called before the fragment is destroyed.

Callback method onPause is called when fragment is killed or every time the fragment becomes inactive but still visible. Callback method onStop is called when fragment moves to background. These call back methods onPause and onStop are called when corresponding methods in the activity are called.

Below is the order in which callback methods are called when fragment is destroyed for example when screen orientation is changed.

Event Handling in Fragments

You can handle input events from views in the user interface of fragments. Similar to input events handling in the activity, to handle input events in fragments, first get the view and add listener to it. For example, in onCreateView method, find button object by calling findViewById on the instantiated View object and add listener to it as shown below.

Back Stack Behavior with Fragments

To add Fragment transitions to back stack, you need to call, while adding, removing or replacing fragments, addToBackStack method on FragmentTransaction before calling commit. This way, when user clicks back button, it takes the user back through history of fragments.

Fragment and Activity Communication

Fragment can access activity by calling getActivity() method and perform actions such as calling methods in activity, getting data from activity by calling a method in the activity and finding views in the activity layout.

Activity can also get the reference to Fragment object and call its methods. To get data from fragment, activity can call a method in fragment which returns data.

Sending Data to Fragment from Activity

One way to get data from activity is by calling a method on the activity that returns data as shown above. Data can also be sent to fragment when it is created by adding data to bundle.

Read the data in onCreateView method of the fragment by calling getArguments() method to get the bundle and calling appropriate methods on it to read values from it.

Sending Data from Fragment to Activity

Fragment can send data to activity by calling a setter method in the activity.

Fragment and Fragment Communication

Since Fragments should be independent, Fragment to fragment communication should not be direct instead it should be done via host activity. To send data from one fragment to another fragment, Fragment should get host activity object and call one of its methods to send data to other fragment, then the activity in turn should obtain the second fragment object and call its method passing the data received from fragment one.

In order to prevent tight coupling between fragment and activity, we should use interface which defines methods for data communication from source fragment to activity.

In the example below, search activity contain two fragments, search and search results fragments. Search fragment passes results to search results fragment via activity.

Interface

Activity

Activity Layout

Search Fragment

Search Fragment Layout

Search Results Fragment

Search Results Fragment Layout

Fragment Transitions

You can add animation to fragment transitions. Fragment allows you to add animation for enter and exit transitions. To add enter transition, you need to call setEnterTransition() method on the Fragment object passing animation object to it. To add exist transition, call setExitTransition() method on the Fragment object.

You can create transition object by instantiating one of the transition classes such as Fade, Slide and Explode and setting required properties.

Fragment Enter Transition Example

Fragment Exit Transition Example

Fragments Custom Animations

You can define animation in xml and use it for fragment transitions. To add custom animation, you need to call setCustomAnimation method on fragment object passing resource ids of enter and exit animations.

You need to define animation xml resources for fragment enter and exit transitions and save them in the res/anim folder.

Below xml defines scale animation.

Below xml defines translate animation.

Fragment Examples

Below some of the example which use fragments.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Оцените статью