Android text in shape

Drawable. Фигуры и градиенты

Shape и ShapeDrawable

Фигуры являются подмножеством Drawable-ресурсов.

Данный вид ресурсов на основе класса ShapeDrawable позволяет описывать простые геометрические фигуры, указывая их размеры, фон и контур с помощью тега .

Можно создавать ресурсы фигур на основе стандартных фигур вроде прямоугольника, эллипса, линии. Для использования ресурсов фигур нужно создать в подкаталоге res/drawable XML-файл, в котором будет присутствовать тег , который в свою очередь может содержать дочерние элементы , ,

Имя файла без расширения будет служить идентификатором (ID): R.drawable.filename в Java-коде и @[package:]drawable/filename в XML-файлах.

Элементы фигуры

— отступы. Возможные атрибуты: android:left, android:top, android:right, android:bottom

  • — размеры фигуры. Возможные атрибуты: android:height, android:width
  • — сплошной цвет для фигуры. Возможные атрибуты: android:color
  • — контур фигуры. Возможные атрибуты: android:width, android:color, android:dashGap (расстояние между черточками), android:dashWidth (длина пунктирной черточки)
  • rectangle (Прямоугольник)

    shape_rect.xml — Атрибут android:shape здесь необязателен: rectangle — это значение по умолчанию.

    Пример с градиентным прямоугольником в качестве разделителя

    Создадим файл separator.xml:

    В разметке приложения добавим код:

    У первого разделителя ширина 1dp, у второго — 3dp. Получили красивую полоску.

    У прямоугольников можно скруглить углы при помощи тега corners

    Можно закруглить углы по отдельности:

    oval (Эллипс)

    Другой вариант с пунктиром:

    ring (Кольцо)

    shape_ring.xml — Для кольца имеются дополнительные атрибуты:

    innerRadius Внутренний радиус innerRadiusRatio Отношение между внешним и внутренним радиусами. По умолчанию равно 3 thickness Толщина кольца (т.е. разница между внешним и внутренним радиусами) thicknessRatio Отношение ширины кольца к его толщине. По умолчанию равно 9

    line (Горизонтальная линия)

    shape_line.xml — Линия может быть только горизонтальной

    Градиенты: gradient и GradientDrawable

    Тег gradient (класс GradientDrawable) позволяет создавать сложные градиентные заливки. Каждый градиент описывает плавный переход между двумя или тремя цветами с помощью линейного/радиального алгоритма или же используя метод развертки.

    Тег gradient внутри тега shape. Основные атрибуты: type, startColor (обязателен), endColor (обязателен) и middleColor (необязателен). Также иногда оказывается полезным атрибут centerColor.

    Используя атрибут type, вы можете описать свой градиент:

    linear

    • android:type=»linear» можно опустить, он так и есть по умолчанию. Отображает прямой переход от цвета startColor к цвету endColor под углом, заданным в атрибуте angle.
    • Атрибут android:angle используется только линейным градиентом и должен быть кратным значению 45.

    Дополнительный материал: Android Dev Tip #3 — помните о прозрачности, который может привести к другому результату.

    Также можно задействовать атрибуты centerX и centerY.

    radial

    Интересный эффект получается при использовании множества радиальных градиентов.

    sweep

    Рисует развёрточный градиент с помощью перехода между цветами startColor и endColor вдоль внешнего края фигуры (как правило, кольца).

    Можно использовать атрибуты android:centerX и android:centerY.

    Попробуйте также такой вариант.

    А почему бы не повращать?

    Примеры с shape

    Закругляем уголки у компонентов

    Создадим отдельный файл res/drawable/roundrect.xml и с его помощью скруглим уголки у LinearLayout, ImageView, TextView, EditText:

    В разметке активности пишем следующее:

    Овальный кабинет

    В Белом доме есть Овальный кабинет. Если вам придётся писать приложение для администрации президента США, то все элементы нужно сделать овальными. Создадим файл res/drawable/oval.xml:

    Заменим в предыдущем примере android:background=»@drawable/roundrect» на android:background=»@drawable/oval».

    Источник

    Android Shape Drawables Tutorial

    Nov 3, 2017 · 6 min read

    Have you ever wanted to reduce your Android application’s size or make it look more interesting? If yes, then you should try out ShapeDrawables.

    First, we will go over the advantages and disadvantages of the ShapeDrawables. Then we will create some Drawables that could be used in your app and lastly for the grand finale we will try to replicate a gradient as can be seen in the Spotify app/website.

    Why should you use ShapeDrawables?

    When you want to use PNG or JPEG images in your applic a tion, you have to provide multiple copies of the same image for different screen densities. That, of course, clutters your app with copies of the same image. Yes, sometimes that is the path we have to choose because we can’t use Drawables for every single case, but we can dramatically reduce our application’s size if we can use Drawables instead. ShapeDrawables are a series of commands that tell how to draw something on the screen. That is why they can be resized and stretched as much as we want, without losing any quality. We can recolor and manipulate them even when the app is running and use the same ShapeDrawable multiple times in our app. Since ShapeDrawables are a subclass of the Drawable abstract class, we can use them in methods where a Drawable is expected. Click for the documentation of the ShapeDrawable.

    Читайте также:  Андроид активатор что это

    Are there any disadvantages?

    Of course, just like I have mentioned before we can’t use them in every case. I have said before that ShapeDrawable class is a subclass of the Drawable abstract class. There are other subclasses as well and every one of them has its own use case. You can click here to check other Drawable types and figure out which one is right for your case. Another issue is that they took a bit longer to draw than a Bitmap since there is a lot of parsing and drawing going on behind the scenes. But I think that is not a huge problem if your Drawables are simple.

    My opinion is that you should use Drawables (ShapeDrawables) wherever you can, because they are easy to modify and they don’t take much space.

    Let’s start coding

    First let’s take a look at a simple example and then we will recreate a gradient as can be seen in the Spotify app/website.

    Create a simple gradient ShapeDrawable in XML

    First create a new drawable resource file.

    Right click on res/drawable > New > Drawable resource file > give your file a name > use shape as a root element > click Ok

    Shape root element defines that this is a ShapeDrawable.

    This is how the first example looks like:

    Источник

    What’s your text’s appearance?

    Understanding how to declaratively style text on Android.

    When styling text in Android apps, TextView offers multiple attributes and different ways to apply them. You can set attributes directly in your layout, you can apply a style to a view, or a theme to a layout or perhaps set a text appearance. But which should you use? What happens if you combine them?

    This article outlines the different approaches to declaratively styling text (i.e. when you inflate an XML layout), looking at their scope and precedence and when you should use each technique.

    You really should read the whole post but here’s a summary.

    Be aware of the precedence order of different styling techniques — if you’re trying to style some text and not seeing the results you expect then your changes are likely being overridden by something higher up in this hierarchy:

    I’d suggest this workflow for styling text:

    1. Set any app wide styling in a textViewStyle default style in your theme.
    2. Set up a (small) selection of TextAppearance s your app will use (or use/extend from MaterialComponent’s styles) and reference these directly from your views
    3. Create styles setting any attributes not supported by TextAppearance (which themselves specify one of your TextAppearances ).
    4. Perform any unique styling directly in your layout.

    Show some style

    While you can directly set TextView attributes in your layout, this approach can be tedious and error prone. Imagine trying to update the color of all text views in your app this way 🙀. As with all views, you can (and should!) instead use styles to promote consistency, reuse and enable easy updates. To this end, I’d recommend creating styles for text whenever you’re likely to want to apply the same styling to multiple views. This is extremely simple and largely handled by the Android view system.

    What’s happening under the hood when you set a style on a view? If you’ve ever written a custom view, you’ve likely seen a call to context.obtainStyledAttributes(AttributeSet, int[], int, int) . This is how the Android view system delivers the attributes specified in your layout to the view. The AttributeSet parameter can essentially be thought of as a map of the XML parameters you specify in your layout. If this AttributeSet specifies a style then the style is read first, then the attributes specified directly on the view are applied on top of that. In this way we arrive at our first rule of precedence.

    Читайте также:  Файловая система android windows

    Attributes defined directly on a view always “‘win” and will override those specified in a style. Note that the combination of the style and view attributes are applied; defining an attribute on a view that also appears in the style doesn’t discard the entire style. It’s also interesting to note that there’s no real way in your views to determine where styling is coming from; it’s resolved by the view system for you in this single call. You can’t receive both and pick.

    Whilst styles are extremely useful, they do have their limits. One of which is that you can only apply a single style to a view (unlike something like CSS on the web where you can apply multiple classes). TextView however, has a trick up its sleeve, it offers a TextAppearance attribute which functions similarly to a style . If you supply text styling via a TextAppearance that leaves the style attribute free for other styling which sounds useful. Let’s take a closer look at what TextAppearance is and how it works.

    TextAppearance

    There’s nothing magical about TextAppearance (like a secret mode to apply multiple styles that Android doesn’t want you to know about. 1!), TextView does some very helpful legwork for you. Let’s peek at some of TextView ’s constructor to see what’s going on.

    So what is happening here? Essentially TextView first looks if you’ve supplied android:textAppearance , if so it loads that style and applies any properties it specifies. Later on, it then loads all attributes of the view (which remember, includes the style) and applies them. We therefore arrive at our second precedence rule:

    Because the text appearance is checked first, any attributes defined either directly on a view or in a style will override the text appearance.

    There’s one other caveat to be aware of with TextAppearance which is that is supports a subset of styling attributes that TextView offers. To understand this, let’s go back to this line:

    We’ve looked at the 4 arg version of obtainStyledAttributes , this 2 arg version is slightly different. It instead looks at a given style (as identified by the first id parameter) and filters it to only the attributes in this style which appear in the second attrs array param. As such the styleable android.R.styleable.TextAppearance defines the scope of what TextAppearance understands. Looking at the definition of this we can see that TextAppearance supports many but not all attributes that TextView supports.

    Styling attributes supported by TextAppearance s

    Some common TextView attributes not included are lineHeight[Multiplier|Extra] , lines , breakStrategy & hyphenationFrequency . TextAppearance works at the character level, not paragraph so attributes affecting the whole layout are not supported.

    So TextAppearance is very useful, it lets us define a style focused on text styling attributes and leaves a view’s style free for other uses. It does however have a limited scope and is at the bottom of the precedence chain, so be aware of its limitations.

    Sensible defaults

    When we took a look at how the Android view system resolved attributes ( context.obtainStyledAttributes ) we actually simplified things a little. This calls through to theme.obtainStyledAttributes (using the current Theme of the Context ). Checking the reference this shows the precedence order we looked at before and specifies 2 more places it looks to resolve attributes: the view’s default style and the theme.

    We’ll come back to the theme but let’s take a look at default styles. What the heck is a default style? To answer this I think it’s illustrative to take a quick detour from TextView and look at the humble Button . When you drop a into your layout, it looks something like this.

    Why? If you look at the source code to Button , it’s pretty sparse:

    That’s it! The entire class (less comments). You can check here. I’ll wait. So where does the background, the capitalized text, the ripple etc all come from? You might have missed it, but it’s all in the 2 arg constructor; the one called when a layout is inflated from XML. It’s the last param which specifies a defaultStyleAttr of com.android.internal.R.attr.buttonStyle . This is the default style which is essentially a point of indirection allowing you to specify a, well, style to use by default. It doesn’t directly point to a style, but lets you point to one in your theme which it will check when resolving attributes. And that’s exactly what all themes you’d typically inherit from do to provide the default look and feel for common widgets. Looking at the Material theme for example, it defines @style/Widget.Material.Light.Button and it is this style which supplies all of the attributes, which theme.obtainStyledAttributes will deliver if you don’t specify anything else.

    Читайте также:  Фортнайт андроид для слабых телефонов

    Going back to TextView , it also offers a default style: textViewStyle . This can be very handy if you want to apply some styling to each and every TextView in your app. Say you wanted to set a default line spacing multiplier of 1.2 throughout. You could do this through style s/ TextAppearance s and try to enforce this through code review (or perhaps even a fancy custom Lint rule) but you’d have to be vigilant and be sure to onboard new team members and be careful with refactors etc.

    A better approach might be to specify your own default style for all TextView s in the app, encoding the desired behavior. You can do this by setting your own style for textViewStyle which extends from the platform or MaterialComponents/AppCompat default.

    So factoring this in, our precedence rules become:

    View > Style > Default Style > TextAppearance

    As part of the view systems attribute resolution, this slots in after styles (so anything in a default style is trumped by an applied style or view attribute) but still will override a text appearance. Default styles can be pretty handy. If you’re ever writing your own custom view then they can be a powerful way to implement default behavior while allowing easy customization.

    If you’re subclassing a widget and not specifying your own default style then be sure to use the parent classes default style in your constructors (don’t just pass 0). For example, if you’re extending AppCompatTextView and write your own 2 arg constructor, be sure to pass android.R.attr.textViewStyle as the defaultStyleAttr (like this) otherwise you’ll lose the parent’s behavior.

    Theme

    As mentioned before, there’s one (final, I promise) way to provide styling information. The other place theme.obtainStyledAttributes will look is directly in the theme itself. That is if you supply a style attribute like android:textColor in your theme, the view system will pick this up as a last resort. Generally it’s a Bad Idea™ to mix theme attributes and style attributes i.e. something you’d apply directly to a view should generally never be set on a theme (and vice versa) but there are a couple of rare exceptions.

    One example might be if you’re trying to change the font throughout your app. You could use one of the techniques above but manually setting up styles/text appearances everywhere would be repetitive and error prone and default styles only work at the widget level; subclasses might override this behavior e.g. buttons define their own android:buttonStyle which wouldn’t pick up your custom android:textViewStyle . Instead you could specify the font in your theme:

    Now any view which supports this attribute will pick this up unless overridden by something with higher precedence:

    View > Style > Default Style > Theme > TextAppearance

    Again, as this is part of the view styling system, it will override anything supplied in a text appearance, but be overridden by any more specific attributes.

    Be mindful of this precedence. In our app-wide-font example you might expect Toolbar s to pick up this font as they contain a title which is a TextView . The Toolbar class itself however defines a default style containing a titleTextAppearance which itself specifies android:fontFamily , and directly sets this on the title TextView , overriding the theme level value. Theme level styling can be useful, but is easily overridden so be sure to check that it’s applied as expected.

    Источник

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