Import view android studio

Урок 19. Android Data Binding. Код в layout. Доступ к View

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

Полный список уроков курса:

Продолжаем говорить про DataBinding. Мы уже рассмотрели, как можно помещать значения из объектов в TextView. Но биндинг этим не ограничивается и дает нам возможность писать код прямо в layout.

Давайте рассмотрим примеры, когда это может понадобиться.

Есть класс Employee:

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

Экран будет таким:

А вызов биндинга таким:

Ничего необычного. Все так же, как и в прошлом уроке.

Но при запуске получим ошибку: android.content.res.Resources$NotFoundException: String resource ID #0x2710

Так произошло, потому что биндинг попытался отобразить поле salary в TextView. Он просто выполнил код setText(employee.salary). И т.к. salary у нас имеет тип int, то TextView решил, что ему передают идентификатор строкового ресурса. И, конечно, он не нашел такую строку в strings.xml.

Это довольно часто возникающая ошибка. И в коде мы обычно решаем ее с помощью String.valueOf():

Биндинг позволяет сделать нам то же самое прямо в layout:

Т.е. внутри @ < . >мы можем писать простейший код и он будет выполнен.

Запустив приложение, мы увидим зарплату в TextView.

Рассмотрим еще несколько примеров:

Отображение в одном TextView сразу двух полей Employee

Обратите внимание на кавычки. Т.к. нам нужны двойные кавычки, чтобы добавить запятую между name и address, то весь этот код мы помещаем в одинарные кавычки.

Видимость View в зависимости от значения поля

Адрес будет отображен, только если он не пустой. А при пустом адресе видимость этого TextView будет GONE.

Обратите внимание, что мы здесь используем классы TextUtils и View. Если сейчас попытаться запустить приложение, то мы получим следующую ошибку: Identifiers must have user defined types from the XML file. TextUtils is missing it

Биндинг говорит, что не знает ничего про TextUtils. Нам надо добавить его в import. Делается это в секции data.

Теперь биндинг знает, какие классы мы имеем ввиду

Т.е. это аналогично тому, как в java коде вы пишете:

и после этого можете использовать эти классы.

Использование resources значения: strings, dimens и пр.

Если адрес пустой, то показываем заглушку из strings.

В примерах выше мы использовали в layout только одну переменную — Employee. Давайте добавим еще одну.

Создадим новый класс, который будет содержать информацию об отделе

Добавим переменную типа Department в layout

И используем ее:

В одном TextView показываем данные из двух переменных.

Код выполнения биндинга будет выглядеть так:

Для переменной Department в классе MainActivityBinding был сгенерирован отдельный метод setDepartment.

Можно немного усложнить логику и показывать название отдела, только если мы передали объект Department в биндинг:

Показываем отдел, если department не null

Биндинг умеет работать и с коллекциями. Например, если в Employee есть поле со списком хобби:

то, в layout мы можем отобразить первое хобби из списка следующим образом:

Если нам необходимо использовать список, как отдельную переменную в layout, то variable будет выглядеть так:

Ограничения XML не позволяют просто так использовать символы . Поэтому их приходится заменять спецсимволами .

То же самое описание переменной, но List вынесен в импорт:

Map коллекции описываются аналогично:

Получение значения по ключу:

В официальной документации вы можете посмотреть полный список возможностей написания кода в layout.

Если нам нужны какие-либо View из нашего layout, то их можно получить из биндинга. Для этого необходимо, чтобы View имело id.

Например, если в layout есть поле:

то мы можем получить его из биндинга так:

Также можно получить корневое View методом getRoot:

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Android SDK: Creating Custom Views

The Android platform provides an extensive range of user interface items that are sufficient for the needs of most apps. However, there may be occasions on which you feel the need to implement a custom user interface for a project you are working on. In this tutorial we will work through the process of creating a custom View.

Читайте также:  Как убрать свой аккаунт гугл с андроид

To create and use our custom View, we will extend the View class, define and specify some custom attributes, add the View to our layout XML, override the onDraw method to tailor the View appearance and manipulate it from our app’s main Activity.

Step 1: Create an Android Project

Create a new Android project in Eclipse. You can choose whatever settings you like as long as your app has a main Activity class and a layout file for it. We do not need any amendments to the Manifest file. In the source code download file the main Activity is named «LovelyActivity» and the layout file is «activity_lovely.xml» — alter the code to suit your own names if necessary. We will be creating and adding to a few additional files as we go along.

Step 2: Create a View Class

Our custom View can extend any of the existing Android View classes such as Button or TextView. However, we will create a direct subclass of View. Extending an existing class allows you to use the existing functionality and styling associated with that class, while providing processing to suit your own additional needs.

Create a new class in your application by selecting the app’s main package in Eclipse and choosing «File», «New», «Class». Enter a name of your choice and click «Finish». The tutorial code uses the class name «LovelyView» — you will need to alter it in all of the below code if you choose a different name. Make your new class extend View by adding to its opening declaration line:

Add the following import statements above this:

Step 3: Create Attribute Resources

In order to use our custom View as we would use a standard View (i.e. set its attributes in layout XML and refer to them in our Java code), we will declare attribute resources. In Eclipse, create a new file in your project «res/values» folder by selecting it and choosing «File», «New», «File». Enter «attrs.xml» as the file name and click «Finish».

In the attributes file we first need to indicate that we are listing resources, so add the following parent element:

Inside this element, we are going to declare three attributes for the View that will allow us to style it. Let’s keep things relatively simple — the View is going to display a circle with some text in the middle. The three attributes will be the circle color, the text String, and the text color. Add the following inside your resources element:

The declare-styleable element specifies the View name. Each attribute has a name and format. We will be able to specify these attributes in the layout XML when we add the custom View and also retrieve them in the View class. We will also be able to retrieve and set the attributes from our Java Activity class. The values provided for each attribute will need to be of the type listed here as format.

Step 4: Add the View to the Layout

Let’s add an instance of the custom View to our app’s main layout file. In order to specify the custom View and its attributes, we need to add an attribute to the parent layout element. In the source download, it is a RelativeLayout but you can use whichever type you prefer. Add the following attribute to your layout’s parent element:

Alter «your.package.name» to reflect the package your app is in. This specifies the namespace for our app, allowing us to use the attributes we defined within it. Now we can add an instance of the new View. Inside the layout, add it as follows:

Again, alter the package name to suit your own, and the class name if necessary. We will use the ID to refer to the View in our Activity code. Notice that the element lists standard View attributes alongside custom attributes. The custom attributes are preceded by «custom:» and use the names we specified in our attributes XML file. Note also that we have specified values of the types we indicated using the format attributes in the «attrs.xml» file. We will retrieve and interpret these values in our View class.

Читайте также:  Угадай мелодию андроид полная версия

Step 5: Retrieve the Attributes

Now let’s turn back to the View class we created. Inside the class declaration, add some instance variables as follows:

We will use the first three of these to keep track of the current settings for color and text. The Paint object is for when we draw the View. After these variables, add a constructor method for your class:

As we are extending the View class, the first thing we do is call the superclass method. After the super call, let’s extend the method to setup the View. First instantiate the Paint object:

Now let’s retrieve the attribute values we set in XML:

This typed array will provide access to the attribute values. Notice that we use the resource name we specified in the «attrs.xml» file. Let’s now attempt to retrieve the attribute values, using a try block in case anything goes wrong:

We read the attributes into our instance variables. Notice that we use the names we listed for each in «attrs.xml» again. The colors are retrieved as integer values and the text label as a String.

That’s the constructor method complete — by the time it has executed, the class should have retrieved the selected View attributes we defined in the attribute resources file and set values for in the layout XML.

Step 6: Draw the View

Now we have our View attributes in the class, so we can go ahead and draw it. To do this, we need to override the onDraw method. Add its outline after your constructor method as follows:

Since we’re going to draw a circle, let’s get some information about the available space, inside the onDraw method:

Now we can calculate the circle radius:

Now let’s set some properties for painting with:

Now we will use the selected circle color as stored in our instance variable:

This means that the circle will be drawn with whatever color we listed in the layout XML. Let’s draw it now using these details:

Now let’s add the text. First set the color using the value retrieved from the layout XML:

Now set some more properties:

Finally we can draw the text, using the text string retrieved:

That’s onDraw complete.

Step 7: Provide Get and Set Methods

When you create a custom View with your own attributes, it is recommended that you also provide get and set methods for them in your View class. After the onDraw method, first add the get methods for the three customizable attributes:

Each method simply returns the value requested. Now add the set methods for the color attributes:

These methods accept int parameters representing the color to set. In both cases we update the instance variable in question, then prompt the View to be redrawn. This will make the onDraw method execute again, so that the new values affect the View displayed to the user. Now add the set method for the text:

This is the same as the other two set methods except for the String parameter. We will call on these methods in our Activity class next.

Step 8: Manipulate the View from the Activity

Now we have the basics of our custom View in place, let’s demonstrate using the methods within our Activity class. In the app’s main Activity class, add the following import statements:

Before the onCreate method, inside the class declaration, add an instance variable representing the instance of the custom View displayed:

Inside the onCreate method, after the existing code, retrieve this using its ID as included in the XML layout file:

To demonstrate setting the View attribute values from the Activity, we will add a simple button. Open your layout file and add it after the custom View element:

We specify a method to execute on user clicks — we will add this to the Activity class. First add the String to your «res/values/strings» XML file:

Now go back to the Activity class and add the method listed for clicks on the button:

Let’s use the set methods we defined to update the custom View appearance:

This is of course just to demonstrate how you can interact with a custom View within your Activity code. When the user clicks the button, the appearance of the custom View will change.

Читайте также:  System adapter андроид вирус

Conclusion

In general, it’s advisable to use existing Android View classes where possible. However, if you do feel that you need a level of customization beyond the default settings, creating your own custom Views is typically straightforward. What we have covered in this tutorial is really just the beginning when it comes to creating tailored Android user interfaces. See the official guide for information on adding interactivity and optimization to your customizations.

Источник

Android компонент с нуля

Задание:

Разработать кнопку-бегунок, которая работает следующим образом: прямоугольная область, слева находится блок со стрелкой, показывающий направление сдвига:

Пользователь зажимает стрелку и переводит её в право, по мере отвода, стрелка вытягивает цветные квадратики:

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

Подготовка

Для создания нового компонента создадим новый проект. Далее создаём новый класс с именем «CustomButton», в качестве предка используем класс «View». Далее создадим конструктор класса и в итоге наш будущий компонент будет иметь вид:

Теперь приступаем к написанию кода класса. Прежде чем начать писать код, скиньте в папку /res/drawable-hdpi, изображение разноцветной ленты. В конструкторе нужно перво наперво инициализировать все объекты и сделать все предварительные настройки. Делаем следующее:
1 — Копируем ссылку на контекст основной активности;
2 — Загружаем подготовленную заготовку-полоску разделённую цветными квадратиками;
3 — Настраиваем компонент необходимый для рисования на поверхности/

Также объявим объекты в начале класса:

Теперь нам необходимо переопределить процедуру настройки размеров компонента — onMeasure. Я специально сделал постоянные размеры для компонента (300*50) чтобы не усложнять пример. Процедура будет иметь вид:

Теперь переопределим процедуру перерисовки компонента «onDraw». Данная процедура вызывается каждый раз когда необходимо перерисовать компонент. Процедура будет иметь вид:

Заготовка для нашего нового компонента готова, давайте поместим её на главную активность. Во первых разместим на главной поверхности новый LinearLayout, под именем «LinearLayout1». Далее в конструкторе класса создадим класс для новой кнопки, создадим класс реализации«LinearLayout1» и добавим кнопку на поверхность. Класс активности будет иметь вид:

Если вы запустите проект на выполнение то на устройстве (эмуляторе) вы увидите примерно следующее:

Функционал

Теперь приступим к реализации анимации и реакции на внешние события. Когда пользователь нажимает на компонент интерфейса, предком которого является View, то автоматически генерируются события, в частности можно отследить координаты нажатия на компонент, и этапы нажатия (нажали, подвигали, отжали). Поэтому требуется переопределить процедуру onTouchEvent, отвечающую за внешние события. Процедура имеет один аргумент «MotionEvent event», он содержит в себе все параметры текущего события. Извлекаем эти параметры следующим образом:

Приводим процедуру к следующему виду:

Каждую строчку расписывать не буду, определю только главную идею. Пользователь нажимает на стрелку компонента, это действие фиксируется в переменной _Last_Action = 1, также фиксируем что пользователь не вытянул ни одного кубика из ленты — _X = 0. Далее отслеживаем перемещение пальца по компоненту и вычисляем сколько кубиков должно показаться на экране, для этого вычисляем _X. Принудительная перерисовка происходит с помощью команды invalidate(). В конце фиксируем отжатие пальца и запускаем таймер, если пользователь вытянул хотя бы один кубик. Таймер необходим чтобы возвращать полоску в исходное состояние не резко, а постепенно.

Теперь реализуем сам таймер, который будет возвращать полоску в исходное положение. Код таймера будет иметь вид:

В данной процедуре происходит цикличное выполнение операции уменьшения значения переменной _X на 1, тем самым показывая какой сектор должен быть показан на компоненте. Так как из дополнительных потоков нельзя влиять на внешний вид компонента, приходится посылать сообщения перерисовки через Handle. Поэтому в конструктор класса добавим реализацию перехвата сообщений для Handle и перерисовку внешнего вида виджета:

Теперь осталось изменить процедуру перерисовки виджета, а именно строку позиционирования ленты на поверхности (ширина одного квадратика на ленте, равна 60 pix, а общая длинна составляет 300 pix):

Добавим все переменные в начало реализации класса.
В итоге класс будет меть вид:

Внешние сообщения

Сильно мудрить не будем, реализуем событие что «лента спрятана» с помощью широковещательных сообщений. В реализации таймера добавим строки отправки сообщений:

В переменной «Name» хранится имя нашего компонента. Для сохранения имени, создадим дополнительную процедуру:

Добавим в блок объявления объектов имя компонента — public String Name.
Теперь в конструкторе нашей активности добавим перехватчик широковещательных сообщений:

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

Источник

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