- Android и кастомные шрифты или «Да здравствует API 26»
- Как было раньше. Краткий обзор
- view.xml
- CustomFontTextView.class
- Но все изменилось в API 26
- Using the App Toolbar
- Android и кастомные шрифты или «Да здравствует API 26»
- Как было раньше. Краткий обзор
- view.xml
- CustomFontTextView.class
- Но все изменилось в API 26
- Android Toolbar Tutorial – XML Layout and Kotlin
- Android Tutorial
- What is Android Toolbar?
- Toolbar Gradle Dependencies
- Android Apps Default Toolbar
- Toolbar from Themes
- Toolbar XML Layout
- 1. Setting Toolbar Background Color
- 2. Setting the Theme
- 3. Setting title, subtitle, icons
- 4. Toolbar Preview
- Android Toolbar Themes
- Android Custom Toolbar
- Creating Toolbar using Kotlin Code
Android и кастомные шрифты или «Да здравствует API 26»
Как было раньше. Краткий обзор
Если было много view где требовались нестандартные шрифты, то мы использовали что-то вроде такого:
view.xml
CustomFontTextView.class
И это я пропустил огромный кусок который отвечает за то, чтобы не писать каждый раз путь к шрифту, а указывать
Ну, или шли на гитхаб и в результате находили Calligraphy (7000 звезд!)
Ни для кого не секрет что этот подход содержал много минусов как в огромном количестве boilerplate кода, так и в том, чтобы сделать это эффективно и где-нибудь не утечь по памяти запрашивая каждый раз Typeface.
Но все изменилось в API 26
Похоже, гугл наконец-то сдался и решил отказаться от навязывания Roboto и сделал удобное подключение сторонних шрифтов, за что ему огромное спасибо.
Линк для тех, кто любит читать в оригинале.
Теперь подключение состоит всего из нескольких несложных шагов:
1. Создаем папку font в res
Resource type выбираем font
2. Перетаскиваем в новую папку все нужные нам в проекте шрифты
3. Создаем файл для семейства шрифтов.
Обратите внимание: я сразу добавил в пример то как должен выглядеть файл, если вы хотите поддерживать и более старые версии Андроида. (Начиная с 14). Если вам повезло и у вас таргет только на супер-новые девайсы, то ваш файл сократится в 2 раза
Ну а дальше остается только наслаждаться сборкой
Использование в TextView
Используем в стилях
И у вас больше не болит голова об эффективности 🙂
Источник
Using the App Toolbar
Toolbar was introduced in Android Lollipop, API 21 release and is the spiritual successor of the ActionBar. It’s a ViewGroup that can be placed anywhere in your XML layouts. Toolbar’s appearance and behavior can be more easily customized than the ActionBar.
Toolbar works well with apps targeted to API 21 and above. However, Android has updated the AppCompat support libraries so the Toolbar can be used on lower Android OS devices as well. In AppCompat, Toolbar is implemented in the androidx.appcompat.widget.Toolbar class.ura
There are two ways to use Toolbar:
- Use a Toolbar as an Action Bar when you want to use the existing ActionBar facilities (such as menu inflation and selection, ActionBarDrawerToggle , and so on) but want to have more control over its appearance.
- Use a standalone Toolbar when you want to use the pattern in your app for situations that an Action Bar would not support; for example, showing multiple toolbars on the screen, spanning only part of the width, and so on.
The Toolbar is a generalization of the ActionBar system. The key differences that distinguish the Toolbar from the ActionBar include:
- Toolbar is a View included in a layout like any other View
- As a regular View , the toolbar is easier to position, animate and control
- Multiple distinct Toolbar elements can be defined within a single activity
Keep in mind that you can also configure any Toolbar as an Activity’s ActionBar, meaning that your standard options menu actions will be display within.
Note that the ActionBar continues to work and if all you need is a static bar at the top that can host icons and a back button, then you can safely continue to use ActionBar .
To use Toolbar as an ActionBar, first ensure the AndroidX support library is added to your application build.gradle (Module:app) file:
Second, let’s disable the theme-provided ActionBar. The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar (or the light variant) within the res/values/styles.xml file:
Now you need to add a Toolbar to your Activity layout file. One of the biggest advantages of using the Toolbar widget is that you can place the view anywhere within your layout. Below we place the toolbar at the top of a LinearLayout like the standard ActionBar:
Note: You’ll want to add android:fitsSystemWindows=»true» (learn more) to the parent layout of the Toolbar to ensure that the height of the activity is calculated correctly.
As Toolbar is just a ViewGroup and can be styled and positioned like any other view. Note that this means if you are in a RelativeLayout , you need to ensure that all other views are positioned below the toolbar explicitly. The toolbar is not given any special treatment as a view.
Next, in your Activity or Fragment, set the Toolbar to act as the ActionBar by calling the setSupportActionBar(Toolbar) method:
Note: When using the support library, make sure that you are importing android.support.v7.widget.Toolbar and not android.widget.Toolbar .
Next, we need to make sure we have the action items listed within a menu resource file such as res/menu/menu_main.xml which is inflated above in onCreateOptionsMenu :
For more details about action items in the Toolbar including how to setup click handling, refer to our ActionBar guide. The above code results in the toolbar fully replacing the ActionBar at the top:
From this point on, all menu items are displayed in your Toolbar, populated via the standard options menu callbacks.
In many apps, the same toolbar can be used across multiple activities or in alternative layout resources for the same activity. In order to easily reuse the toolbar, we can leverage the layout include tag as follows. First, define your toolbar in a layout file in res/layout/toolbar_main.xml :
Next, we can use the tag to load the toolbar into our activity layout XML:
and then access the Toolbar by the include id instead:
This allows us to create a consistent navigation experience across activities or configuration changes.
The Toolbar can be customized in many ways leveraging various style properties including android:theme , app:titleTextAppearance , app:popupTheme . Each of these can be mapped to a style. Start with:
Now, we need to create the custom styles in res/values/styles.xml with:
This results in:
In certain situations, we might want to display an app icon within the Toolbar . This can be done by adding this code into the Activity
Next, we need to remove the left inset margin that pushes the icon over too far to the left by adding app:contentInsetStart to the Toolbar :
With that the icon should properly display within the Toolbar as expected.
A Toolbar is just a decorated ViewGroup and as a result, the title contained within can be completely customized by embedding a view within the Toolbar such as:
This means that you can style the TextView like any other. You can access the TextView inside your activity with:
Note that you must hide the default title using setDisplayShowTitleEnabled . This results in:
In certain cases, the status bar should be translucent such as:
To achieve this, first set these properties in your res/values/styles.xml within the main theme:
The activity or root layout that will have a transparent status bar needs have the fitsSystemWindows property set in the layout XML:
You should be all set. Refer to this stackoverflow post for more details.
If you want the status bar to be entirely transparent for KitKat and above, the easiest approach is to:
and then add this style to your res/values/styles.xml within the main theme:
You should be all set. Refer to this stackoverflow post for more details.
We can configure the Toolbar to react and change as the page scrolls:
For example, we can have the toolbar hide when the user scrolls down on a list or expand as the user scrolls to the header. There are many effects that can be configured by using the CoordinatorLayout. First, we need to make sure we add the jetpack libraries to our app/build.gradle file:
Next, inside the activity layout XML such as res/layout/activity_main.xml , we need to setup our coordinated layout with a Toolbar and a scrolling container such as a RecyclerView :
Of course, the RecyclerView could also be replaced with a FrameLayout which could then allow for fragments to be loaded instead:
This type of layout results in the following:
Refer to the guide on CoordinatorLayout and AppBarLayout for additional explanation and specifics. For troubleshooting, refer to this troubleshooting guide.
The proper way of reacting to simple scroll behavior is leveraging the CoordinatorLayout built into the Design Support Library as shown in the previous section. However, there are a few other relevant resources around reacting to scrolling events with a more manual approach:
- Hiding or Showing Toolbar on Scroll — Great guide on an alternate strategy not requiring the CoordinatorLayout to replicate the behavior of the «Google Play Music» app. Sample code can be found here.
- Hiding or Showing Toolbar using CoordinatorLayout — Great guide that outlines how to use CoordinatorLayout to hide the Toolbar and the FAB when the user scrolls.
With these methods, your app can replicate any scrolling behaviors seen in common apps with varying levels of difficulty not captured with the method shown above.
Источник
Android и кастомные шрифты или «Да здравствует API 26»
Как было раньше. Краткий обзор
Если было много view где требовались нестандартные шрифты, то мы использовали что-то вроде такого:
view.xml
CustomFontTextView.class
И это я пропустил огромный кусок который отвечает за то, чтобы не писать каждый раз путь к шрифту, а указывать
Ну, или шли на гитхаб и в результате находили Calligraphy (7000 звезд!)
Ни для кого не секрет что этот подход содержал много минусов как в огромном количестве boilerplate кода, так и в том, чтобы сделать это эффективно и где-нибудь не утечь по памяти запрашивая каждый раз Typeface.
Но все изменилось в API 26
Похоже, гугл наконец-то сдался и решил отказаться от навязывания Roboto и сделал удобное подключение сторонних шрифтов, за что ему огромное спасибо.
Линк для тех, кто любит читать в оригинале.
Теперь подключение состоит всего из нескольких несложных шагов:
1. Создаем папку font в res
Resource type выбираем font
2. Перетаскиваем в новую папку все нужные нам в проекте шрифты
3. Создаем файл для семейства шрифтов.
Обратите внимание: я сразу добавил в пример то как должен выглядеть файл, если вы хотите поддерживать и более старые версии Андроида. (Начиная с 14). Если вам повезло и у вас таргет только на супер-новые девайсы, то ваш файл сократится в 2 раза
Ну а дальше остается только наслаждаться сборкой
Использование в TextView
Используем в стилях
И у вас больше не болит голова об эффективности 🙂
Источник
Android Toolbar Tutorial – XML Layout and Kotlin
Android Tutorial
Android Toolbar widget is used to create menus in the apps. We will learn how to create a Toolbar using the XML layout and Kotlin code. We will implement various toolbar properties in an example Android app.
What is Android Toolbar?
Android Toolbar widget is generally found on the top of the screen. The application title, logo, navigation icon, and the menu bar is displayed inside the toolbar.
The toolbar is the material design replacement for the old and now deprecated ActionBar.
Toolbar Gradle Dependencies
The toolbar is available with the following dependency.
Android Toolbar can be supplied either from the themes or from the layout.
Android Apps Default Toolbar
When you create a new android studio project, you might see that the activity_main.xml doesn’t have any Toolbar defined in the XML. Still, when you see the XML preview, there is a Toolbar with the application name by default at the top.
This is because the following style is defined in the styles.xml, which is ultimately attached in the AndroidManifest.xml file.
Toolbar from Themes
DarkActionBar theme adds the Toolbar at the top of the app by default.
We can change the parent theme in the above image from Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar to remove the Toolbar that is displayed as a part of the activity theme.
Let’s change the theme and add the Toolbar in the activity_main.xml file.
Toolbar XML Layout
We have added the toolbar in our activity_main.xml layout file using the following code.
This will display a Transparent Toolbar with no text or any other items.
We have to add more properties to utilize Toolbar effectively.
1. Setting Toolbar Background Color
We have to add the following XML attribute in our Toolbar tag for the background color.
2. Setting the Theme
We can set the toolbar theme using the following code.
We are using a default theme for the layout. Dark indicates that the text colors would be light (generally white).
We can also create our own custom themes in the styles.xml file.
3. Setting title, subtitle, icons
- Title: app:title=»Androidly Toolbar»
- Subtitle: app:subtitle=»Sub»
- Logo: app:logo=»@android:drawable/ic_menu_call»
- Navigation Icon: app:navigationIcon=»@drawable/ic_menu_black_24dp»
4. Toolbar Preview
Our toolbar looks like the below image after doing all the above changes.
Toggle the theme to @style/ThemeOverlay.AppCompat.Light and you shall see inverted colors.
Android Toolbar Themes
We can create our own custom styles and assign them as a theme on our Toolbar. This will be much easier than adding all those XML properties.
Let’s use the custom theme in the activity_main.xml file.
The AppTheme style gets updated in the AndroidManifest.xml file. Our Toolbar will look like the below image.
Android Custom Toolbar
We can define our own custom views inside a Toolbar. The following layout defines custom views within the toolbar.
Creating Toolbar using Kotlin Code
We can create toolbars programmatically using Kotlin code. Each of the toolbar XML properties has its equivalent Kotlin methods.
The following MainActivity.kt class is defined below.
Using the as operator, we safely typecast the XML view to the toolbar instance.
The setNavigationOnClickListener triggers a toast message when the navigation icon is clicked from the menu.
Источник