Android what is tools context

Пространство имён 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 используется в разметке фрагмента, чтобы вывести макет фрагмента на экране активности.

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-файл следующего содержания.

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

Источник

What is Context in Android?

Android apps are popular for a long time and it is evolving to a greater level as user’s expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across a word context. So what exactly is this context and why is it so important? To answer this question lets first see what the literal meaning of context is:

The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood

Looking at this definition we come across two things:

  • The context tells us about the surrounding information.
  • It is very important to understand the environment which we want to understand.
Читайте также:  Тепловая камера для андроид

Similarly when we talk about the Android Programming context can be understood as something which gives us the context of the current state of our application. We can break the context and its use into three major points:

  • It allows us to access resources.
  • It allows us to interact with other Android components by sending messages.
  • It gives you information about your app environment.

In the official Android documentation, context is defined as:

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

Understanding Context by a Real World Example

Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during the time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So here the room-service person is the context considering you are the single activity and the hotel to be your app, finally , the breakfast, lunch & dinner have to be the resources.

How Does This Work?

1. It is the context of the current/active state of the application.

Usually, the app got multiple screens like display/inquiry/add/delete screens(General requirement of a basic app). So when the user is searching for something, the context is an inquiry screen in this case.

2. It is used to get information about the activity and application.

The inquiry screen’s context specifies that the user is in inquiry activity, and he/she can submit queries related to the app

3. It is used to get access to resources, databases, and shared preferences, etc.

Via Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The context for the respective screen helps to get hold of database data and the shared data across screens

4. Both the Activity and Application classes extend the Context class.

In android, context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the context class.

Types of Context in Android

There are mainly two types of context are available in Android.

  1. Application Context and
  2. Activity Context

The Overall view of the App hierarchy looks like the following:

Читайте также:  Что обозначает значок андроид

It can be seen in the above image that in “Sample Application”, nearest Context is Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only.

Application Context

This context is tied to the life cycle of an application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext() . Some use cases of Application Context are:

  • If it is necessary to create a singleton object
  • During the necessity of a library in an activity

getApplicationContext():

It is used to return the context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a context and often we use “this” to pass the activity context or “getApplicationContext” to pass the application context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext() .

Источник

What is tools:context in Android layout files?

Whenever you create a project in Android Studio or add an activity in Android Studio, then in the layout file of your activity, you must have seen one line that is added automatically to your file, saying:

What is this used for? Do you have any idea? Don’t worry, in this blog, we will learn the need for tools:context in Android layout files. So, let’s get started.

Following is the code that is present(by default) in your layout file when you create an activity:

In the above code, the basic need of tools:context is to tell which activity or fragment the layout file is associated with by default. So, you can specify the activity class name using the same dot prefix as used in Manifest file.

The tools:context has a primary role in defining which Activity or Fragment class has instantiated the layout which is being defined.

By doing so, the Android Studio will choose the necessary theme for the preview automatically and you don’t have to do the preview settings manually. As we all know that a layout file can be associated with several activities but the themes are defined in the Manifest file and these themes are associated with your activity. So, by adding tools:context in your layout file, the Android Studio preview will automatically choose the necessary theme for you.

Apart from this, the tools:context is used for rendering the action bar or it can be used to find the correct place to insert the onClick handlers when you want to perform some click operations.

onClick handlers are an alternative of setOnClickListener().

We can summarize the whole concept by saying that tools:context attribute is used in the root element of the layout file and it tells which activity or fragment the layout file is associated with. It is used for a better preview of the current layout and views.

Hope you learned something new today.

Do share this blog with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website.

Источник

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