Http schemas android com tools

Пространство имён Tools

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

Настало время сорвать покровы и использовать новые возможности.

Привычное пространство имён xmlns:android позволяет настраивать внешний вид и поведение компонентов в Android-приложении. А новое пространство имён xmlns:tools позволяет среде разработки (в нашем случае, Android Studio) правильно отобразить компоненты для просмотра в режиме дизайна.

Причём возможности данного инструмента гораздо выше, чем многие себе представляют.

Для начала приведу простой пример, который многие оценят по достоинству. Представьте себе, что у вас есть компонент пустой TextView, который получает текст с сервера. Чтобы визуально представить себе, как будет выглядеть текст, не соединяясь с сервером, вам нужно временно присвоить какой-нибудь текст. А потом не забыть удалить его при создании релиза. А можно поступить проще. Инструмент tools дублирует многие визуальные атрибуты пространства имён android и вы можете заменить его следующим образом.

В реальности у текстовой метки нет текста, но в окне предварительного просмотра вы можете видеть текст и оценить дизайн. Напомню, что эта настройка относится только к среде разработки, а не к вашему приложению. Поэтому теперь можно не волноваться, что однажды вы забудете удалить временный текст. Попробуйте теперь поменять цвет фона с помощью атрибута tools:background =»#ваш_цвет». Получилось?

Кроме визуальных атрибутов, tools может использоваться для взаимодействия с инструментом Lint, который пытается подсказать при проблемном коде. К этим атрибутам можно отнести

tools:ignore

Атрибут tools:ignore похож по своему поведению на Java-аннотацию @SuppressWarnings, подсказывающему инструменту Lint не обращать внимания на код. Аналогично можно не обращать на какой-то атрибут в XML-файле.

Самый распространённый случай — использование ImageView. Lint всегда недоволен, если у данного компонента нет атрибута android:contentDescription. Профессионально сделанное приложение должно использовать данный атрибут. Но в некоторых ситуациях ImageView может быть вспомогательным элементом экрана, не несущим смысловой нагрузки, например, разделитель. И тогда можно подавить предупреждение следующим образом.

tools:targetApi

Атрибут tools:targetApi работает аналогично аннотации @TargetApi и говорит о минимальной версии API, которая будет использована для ресурсов.

Например, ваш проект использует минимальный уровень minSdkLevel = 15, а вы используете объекты RippleDrawable в качестве ресурсов в общей папке, а не в папке drawable-v21. Но если вы контролируете ситуацию и знаете, что для старых устройств есть другие ресурсы, то можете подавить предупреждение:

tools:locale

Атрибут tools:locale поможет вам подавить предупреждения Lint о неправильном правописании, выступая в качестве грамар-наци. Проблема в том, что Lint содержит проверку орфографии только на английском языке. И если ваши строковые ресурсы содержат русский текст, то его предупреждения бесполезны. Отключаем их:

Рассмотрим теперь другие доступные атрибуты.

tools:context

Атрибут tools:context у корневого элемента позволяет определить связь между макетом и классом активности, в которой данный макет будет реализован. Помогает студии сформировать в окне предварительного просмотра внешний вид, подтягивая нужную тему.

tools:layout

Атрибут tools:layout используется в разметке фрагмента, чтобы вывести макет фрагмента на экране активности.

Читайте также:  Защита для андроида samsung

tools:showIn

Атрибут tools:showIn позволяет указать, какую разметку нужно использовать для вывода в окне предварительного просмотра. Это может пригодиться для тега merge:

tools:menu

Атрибут tools:menu подсказывает среде разработке, какое меню нужно отобразить в окне предварительного просмотра. Также используется в корневом элементе разметки.

Можно через запятую указать несколько меню, заданных в папке res/menu. Также кроме имени XML-файла можно использовать идентификаторы меню без символа @. В окне предварительного просмотра вы можете вызвать меню и нажать на пункт меню — вас сразу перенесёт в нужный файл.

Если не хотите выводить меню, то оставьте пустую строку. Данный атрибут не работает с темой Theme.AppCompat и производных от неё.

tools:actionBarNavMode

Атрибут tools:actionBarNavMode отвечает за внешний вид панели действий ActionBar. Он также размещается в корневом элементе разметки, не работает с темами Theme.AppCompat и Theme.Material и не действует при использовании Toolbar вместо ActionBar.

Доступны три варианта:

tools:listitem / listheader / listfooter

Также можно настроить внешний вид компонентов на основе AdapterViewListView, GridView, ExpandableListView и т.д., указав нужную разметку для отдельных элементов списка, а также заголовка и футера. Появилась поддержка и RecyclerView.

Атрибуты для заголовка и футера могут работать только для ListView, а для GridView не работает.

Для сравнения как выглядят экраны активности с использованием tools: и без него.

Мы видим вкладки, элементы меню, другую разметку для списка.

tools:layoutManager

В RecyclerView можно использовать менеджер разметок с указанием различных параметров.

tools:itemCount

Обычно студия выводит десять элементов списка в RecyclerView. Вы можете изменить это поведение данным атрибутом.

tools:openDrawer

В студии 1.4 появился новый атрибут tools:openDrawer, управляющий состоянием навигационной шторки для DrawerLayout. При значении start будет показана шторка в выдвинутом виде. Доступны значения: start, end, left, right.

tools:minValue/tools:maxValue

Атрибуты для компонента NumberPicker для задания минимального и максимального значения.

tools:src

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

tools:layout_height/tools:layout_width

Ширина и высота.

tools:background

tools:src=»http://developer.alexanderklimov.ru/android/studio/@tools:sample/»

В студии версии 3.0 появились новые возможности. Теперь вы можете задать аватар, имя и случайный текст без создания собственных ресурсов. Это бывает полезно, когда ресурсы берутся из внешнего источника. Вам не нужно создавать временные ресурсы, которые увеличивают размер приложения и которые можно забыть удалить.

Например, можно задать изображение для ImageView:

Если у вас несколько ImageView, то изображения будут разными! Просмотреть весь набор можно в папке ..\plugins\android\lib\sampleData.

Можно задать текст для TextView:

  • tools:text=»@tools:sample/full_names» — полное имя (также first_names, last_names)
  • tools:text=»@tools:sample/cities» — город
  • tools:text=»@tools:sample/us_zipcodes» — индексы США
  • tools:text=»@tools:sample/us_phones» — телефонные номера США в формате (800) 555-xxxx
  • tools:text=»@tools:sample/date/ddmmyy» — дата (date/day_of_week, date/mmddyy, date/hhmm, date/hhmmss)
  • tools:text=»@tools:sample/lorem» — случайный текст
  • tools:text=»@tools:sample/lorem/random» — большой случайный текст

Можно задать случайный фон

Пример применения некоторых атрибутов.

Но это ещё не всё. Если вас не устраивают изображения (там нет котов!) или тексты, предлагаемые студией, то можно задать свои изображения и тексты. Из контекстного меню папки res выбираем New | Sample Data Directory. В модуле app появится папка sampleData. Создайте текстовый файл с именем names и добавьте построчно различные имена: Барсик, Мурзик, Рыжик, Васька и т.д.

Заменим tools:text=»@tools:sample/full_names» на tools:text=»@sample/names». Теперь вместо непонятных иностранных имён будут отображаться правильные нормальные имена.

По такому же принципу можно создать собственные изображения для аватаров. В папке sampleData создайте подпапку avatars (имя произвольное) и разместите в ней нужные файлы изображений.

Читайте также:  Значение по умолчанию андроид как установить

Используем атрибут для аватаров — tools:src=»http://developer.alexanderklimov.ru/android/studio/@sample/avatars».

Можно создать сложный вариант сочетаний имён и городов. Опять в той же папке sampleData создаём JSON-файл следующего содержания.

Можете обращаться к созданному файлу через атрибуты:

Источник

Programming VIP

Very Interesting Programming

Namespaces for XML in Android

Introduction to basic concepts

Namespace

XML namespaces provide a way to avoid element naming conflicts.

For example, there is a student named Lin Xiaoming in School A and a student named Lin Xiaoming in School B. How can we identify these two students with the same name? Namespace will come in handy at this time. A and B can then be considered namespaces. In other words, the namespace contains a collection of specific attributes.

Common Namespaces in Android

The following sections introduce android, tools, and app (custom namespaces), which are common namespaces.

1,android

xmlns:android=»http://schemas.android.com/apk/res/android»
In the Android layout file, we all have to define such a namespace on the root element. Next, we will explain this line of code one by one.
xmlns: xml namespace, declaring that we are going to start defining a namespace
The string in which android is located, which we call namespace-prefix, actually means giving the namespace a name.
http://schemas.android.com/apk/res/android This looks like a URL, but this address is not accessible. In fact, this is a URI (Unified Resource Identifier), so its value is fixed, equivalent to a constant.

With him, you will be prompted to enter something, which can also be understood as a grammar file.

So what does this line of code do? The attributes in the namespace that we write in the code for the root element can be referenced, such as:

In this layout, as long as the attribute begins with android: it refers to the attribute in the namespace. As mentioned above, Android gives the namespace a name, just like we usually define variables, so the name can also be taken as our favorite. For example, if I take it as myns, then the code above We can also write as follows:

2,tools

Next, I will introduce three ways to use tools, which are also his characteristics.

2.1. tools only works at the development stage

We can think of him as a tool namespace, a tool to help developers. It only works at the development stage. When an app is packaged, all tools attributes will be discarded!

For example, basically in the android namespace, we want to test the effect of a component on the screen at the coding stage, and when app is installed on the phone, discard this code, then we can replace android with tools namespace:

This is the layout in the layout. When we switch to the view window (Design), we see that the top of the label is centered.

Then, when we run it on our mobile phone, it’s like this:

As shown above, tools:layoutgravity= «center» is indeed abandoned behind the runtime!

2.2. Viewing Activity Layout Effect in tools:context Development

The use of context is followed by the full package name of an Activty. What does it do?

When we set an Activity theme, it is set in AndroidManifest.xml, and the effect of the theme can only be displayed in Activty after running. With the help of context attribute, we can see the effect of the theme set in Activity in the layout in the development stage.
tools:context=»com.littlehan.myapplication.MainActivity»
By adding this line of code to the layout, you can see the effect of binding the theme to MainActivity in the design view.

Читайте также:  Как удалить рабочие столы для андроид

2.3. Viewing fragment layout effect in tools:layout development

When we load a fragment on Activity, we need to see the effect after loading after running. Is there a way to display it in the layout preview window during the testing phase? The answer is yes, with the help of the layout attribute, for example,
Add such a line of code to the layout:
tools:layout=@layout/yourfragmentlayoutname
In this way, your fragment layout will be previewed on the specified main layout.

3. Customizing Namespaces

If you use DataBinding, you will use the app attribute in xml, which is actually a custom namespace.

Some friends may ask, where is the reflection of self-definition?

In fact, it can also be written as follows:
xmlns:app=»http://schemas.android.com/apk/res/ Complete package name»
Just fill in our package name after res/ However, in my own Android Studio 2.0, this is not recommended, so it is more recommended that you use the first naming method.

Usually custom namespaces are inseparable from custom views. When Android’s own controls can’t meet our needs, we will draw some views ourselves. When we add custom attributes to these customized views, we need to create our own namespaces.

As I said at the beginning, the namespace contains a collection of specific attributes, so the idea is clear, that is to say, the actual process of customizing a namespace is to customize attributes.

We learn about custom namespaces through a simple custom TextView. The process of customizing the View can be divided into the following steps:

Inheriting View Class

Create a class named CustomTextView Inheritance View
(View is the parent class of all views) and implements its three constructions

Drawing Views

Overload the onDraw() method to draw a paragraph of text

Use custom layout

Introducing custom controls into layout

Here, a custom control is introduced into the layout, and we can switch to the view window to see the effect.

But this custom control can not change the font color, font size, custom text and so on in xml. The implementation of this function is actually the process of creating custom attributes in XML and parsing attributes in custom View s.

Custom Properties

Create a new xml file named attrs under the values root directory to customize our attributes (the attributes defined here are the attributes in our custom namespace)

Name defines the name of an attribute
format defines the type of attribute

Parsing attributes

Resolve these attributes in CustomeTextView

Use custom properties

To use custom attributes, you need to customize the attribute namespace by inserting such a line of code under the root element of the layout file:
xmlns:app=»http://schemas.android.com/apk/res-auto»

So we can use custom attributes:

Switch to the view preview window and you can see that the custom properties are in effect:

summary

In Android, namespaces can be divided into three categories:

Among them, the attributes in 1 and 2 namespaces are encapsulated by the system, and the attributes in the third namespace are user-defined.

Added by vijayfreaks on Thu, 18 Jul 2019 04:11:20 +0300

Источник

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