Android studio button statelistanimator

Полируем UI в Android: StateListAnimator

Привет, Хабр! В преддверии старта курса «Android Developer. Professional» мы подготовили для вас перевод еще одного интересного материала.

Большую часть времени разработки нашего Android-приложения мы тратим отнюдь не на работу над пользовательским интерфейсом — мы просто накидываем вьюх и начинаем писать код. Я заметил, что большинство из нас не особо заботится о пользовательском интерфейсе. И я считаю, что это в корне неправильно. Разработчики мобильных приложений должны заботиться также и о UI/UX. Я не говорю «будьте экспертом в мобильном UI», но вы должны понимать язык дизайна и его концепции.

Ранее я написал статью о тенях в материальном дизайне и получил много хороших отзывов. Я хочу поблагодарить всех вас. «Освоение теней в Android» рассказывает о высоте (elevation) и тени (shadow) в Android. Там же я показал, как дополнял ими свою UI библиотеку с открытым исходным кодом. (Scaling Layout).

В этой статье я хочу усовершенствовать свою библиотеку с помощью StateListAnimator и шаг за шагом показать вам, как я это буду делать.

Содержание

В этой статье рассматриваются следующие темы:

Состояния Drawable

В Android есть 17 различных состояний для Drawable.

Возможно, мы даже никогда не встречали некоторые из них. Я не собираюсь углубляться в каждое состояние. В большинстве случаев мы используем pressed , enabled , windows focused , checked и т. д. Если мы не объявляем состояние для drawable, то подразумевается, что это состояние по умолчанию в Android.

Нам нужно понимать эти состояния, чтобы написать наш собственный StateListDrawable.

StateListDrawable

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

Это элемент (item). Он имеет два свойства. Drawable и State.

Это StateListDrawable. Если мы не объявляем состояние (state) для элемента, как я уже упоминал ранее, это означает, что это состояние по умолчанию.

Могу ли я использовать ShapeDrawable?

Да. Вместо использования android:drawable вы можете добавить к своему элементу произвольную форму. Вот элемент с ShapeDrawable.


StateListDrawable

Вы можете использовать StateListDrawable с уровня API 1. Таким образом, для StateListDrawable нет ограничений уровня API.

Вот и все. Теперь у нашего вью есть состояние. Когда пользователь нажимает на него, его цвет будет изменен. Когда пользователь отпустит его, он будет иметь состояние и цвет по умолчанию.

Но погодите секундочку. Clickable? Зачем мы добавили этот атрибут? Нам что, еще и его добавлять нужно? Да. Но только для пользовательских вью. Чтобы это выяснить, нужно время. Кнопки отлично работают без добавления clickable, потому что они по умолчанию clickable. Но если вы хотите использовать StateListDrawable для View, ImageView, Custom View и т. д., вам необходимо добавить атрибут clickable.


StateListDrawable

Я добавил StateListDrawable в этом коммите. Он похож на пример, который я привел выше. Когда пользователь нажимает на лейаут, он окрашивается. Но давайте улучшим это с помощью StateListAnimator.

StateListAnimator

Помните, что когда вы нажимаете FloatingActionButton, его Z значение увеличивается из-за анимации. Это StateListAnimator так сказать за кадром. У некоторых виджетов материального дизайна есть собственный StateListAnimator внутри.

Давайте проясним это с помощью вопроса на StackOverflow.

(Как удалить границу/тень с кнопок lollipop).

Если у виджетов материального дизайна есть собственный StateListAnimator внутри, мы можем установить для них значение null, чтобы удалить эти функцию (не рекомендую, она разработана не просто так.) И сейчас ответ звучит куда более логично.

(Lollipop имеет небольшую неприятную функцию, называемую stateListAnimator , которая обрабатывает высоту кнопок, производя тени.

Удалите stateListAnimator , чтобы избавиться от теней.

У вас есть несколько вариантов как сделать это:

Итак, а как мы можем создать его?

Чтобы понять StateListAnimator, нам нужно понять анимацию свойств объекта (property animation). Я не собираюсь углубляться в анимацию свойств в этой статье. Но по крайней мере, я хочу показать вам основы.

Анимация свойств

Вот самый простой пример свойства в объекте. X — это свойство.

Система property animation — это надежный фреймворк, который позволяет анимировать практически все. Вы можете определить анимацию для изменения любого свойства объекта с течением времени, независимо от того, отображается ли он на экране или нет. Анимация свойства изменяет значение свойства (поля в объекте) в течение заданного периода времени.

X — это свойство. Т — время. Во время анимации свойство X обновляется в заданное время. В целом так работает анимация свойств. Вместо коробки может быть вью или любой объект.

ValueAnimator — это базовый класс для анимации свойств. Вы можете настроить слушатель на обновления ValueAnimator и наблюдать за изменениями свойств.

ObjectAnimator — это класс, который является наследником ValueAnimator . Вы можете использовать ObjectAnimator, если для вас больше подходит следующие:

  • У вас есть объект (любой класс с каким-нибудь свойством).
  • Вы не хотите наблюдать за слушателем ValueAnimator.
  • Вы хотите обновлять свойство объекта автоматически.

Итак, если у нас есть вью (которое является объектом), и мы хотим обновить свойство вью (координата x, координата y, rotation, translation или любое другое свойство, для которого у вью есть геттер/сеттер), мы можем использовать ObjectAnimator. Продолжим создание StateListAnimator.


Кнопка FAB анимирует свое свойство «translationZ» при нажатии и разжатии.

Как я сказал ранее, мы можем использовать свойство объекта напрямую, не наблюдая за изменениями в аниматоре. Каждый View имеет свойство translationZ. Таким образом, мы можем напрямую анимировать translationZ с помощью ObjectAnimator.

Мы можем также объединить несколько objectAnimator> -ов в set> . Изменим еще одно свойство View. Scale X и Scale Y.

Вот результат! Теперь она также увеличивается при нажатии пользователем. А вот коммит.

Вы также можете определить другие свойства в своем animator.xml . Здесь вы можете найти больше информации об использовании ObjectAnimator.

Вот и все. Я планирую написать еще что-нибудь о ValueAnimator и ObjectAnimator. Это отличное API для анимации объекта.

Источник

Creating an Instagram “Like” Animation With StateListAnimators

Nov 5, 2017 · 5 min read

Creating a stateful button is a very common use-case that you might come across in your application. A stateful button, operates very much like a toggle to depict binary values. For example : a post is liked or not liked, user is followed/not followed, article is bookmarked or not etc.

Android provides a very easy way to emulate a checked behavior which does away with a lot of code that might be required to change the icons or the color of the icons when the button is clicked.

StateListDrawable

In Android, t he definition of a Drawable is very flexible. Drawable can encompass bitmaps, colors as well as other drawables themselves.

StateListDrawable is an amazing tool provided by Android (extends Drawable) which lets us define multiple drawables that will be swapped out by Android depending of the state of the element.

StateListDrawable defines predefined “states” that elements can be in. The most common ones are state_checked , state_pressed , state_enabled , state_focussed etc.

Not only can you define drawables so that the icon changes with state change, you can also define borders, fill color, border color etc for each state. This way, a simple element like a Button can have a different look from when it’s disabled to when it’s pressed.

Enough talk, let’s get to the code

Here we have an XML file which emulates a poor man’s Instagram feed post.

The main thing we’re concerned with is :

I’m representing my like button as a CheckBox . Why? More on that in some time.

The android:button=»@null» means that there is no button associated with my CheckBox. The android:checked=»false» is to keep it unchecked by default.

Our main property is the android:background=»@drawable/like_icon» where the like_icon.xml is our StateListDrawable. Let’s take a look at that!

It’s pretty small and compact. We’re defining a which contains all the states for which we want to define custom drawables/properties.

defines the Drawable for the checked state.

defines the default drawable to show.

The icon can be found in Android Studio itself. You can get them by going to File -> New -> Vector Asset and click on the Droid icon which will pull up a list of icons.

So, coming back to CheckBox . Why CheckBox and not ImageView or ImageButton or even a Button . The answer is the Checkable interface defined by Android which gives an element “checkable” abilities. Only CheckBox,CheckedTextView,CompoundButton,RadioButton,Switch,ToggleButton implement Checkable. Hence, our best bet is to use these elements and replace it with our own backgrounds. However, if you want more control over the toggle abilities then you can easily extend, a Button for example and implement Checkable.

After doing this, the toggling looks something like this :

Looks cool, but it will look cooler if there’s an animation associated with it. Because let’s face it, everything is cooler with animation.

Animating a state change is actually a joy. My experience with animations on Android has always been frustrating but with element states, Android has yet another wonderful tool called StateListAnimator

StateListAnimator

It works very similarly to a StateListDrawable. In a you can define different animations for different state of the element. Since we’re trying to emulate Instagram, we’re gonna try and implement something that first increases in size and then goes back to it’s original size, as can be seen in the GIF at the beginning of the article.

Our likeButton element now has an extra property:

To add an animator, we’ll have to add an animator folder in our resources. You can then create a file called scale.xml and your file explorer will look something like this :

Let’s take a look at the animator.

It looks really big, but it’s pretty simple. The animator for both checked and unchecked state is the same, because Instagram does the animation both for liking and not liking the post.

We define three object animators : One to increase the X value from 1 to 1.525, one to increase Y to 1.525 and one to increase the height to 4dp. We also have provided a duration from Android’s default. These three will take care of scaling the image from 1 to 1.525. Now we will define three animators to scale the image back to it’s original size.

Again, pretty trivial stuff. We scale the objects X, Y and Z to 1.0. The interesting property is the android:startOffset and we add that because we don’t want to start this animation till the scaling animation is over.

Once we do that, our app now looks like this!

It’s pretty cool and we’re very close to Instagram’s animation (Except of course the ugly UI and the like icon 😛 ). The only thing it might differ on is the duration which can be tweaked around.

Using StateListAnimators, we can animate all kinds of stuff including state_pressed, state_disabled etc.

Источник

Polishing UI: Android StateListAnimator

Jan 31, 2018 · 6 min read

Most of the time, we don’t spend time to develop our Android app’s UI, we just drag and drop views and start writing our app. I have observed that most of us don’t care that much about the user interface. And I believe that it’s wrong. Mobile developers should care about UI/UX too. I am not saying “Be an expert on mobile UI” but we should understand design language and it’s concept.

Previously I wrote something about material design shadows and I got lots of good feedback. I would like to thank all of you. “Mastering Shadows in Android” explains elevation and shadows in android. And also I applied these changes to my open source UI library. (Scaling Layout).

Mastering Shadows in Android

If we want to create better apps, I believe that we need to follow material design guideline.In general terms, Material…

In this post, I also want to polish my library with StateListAnimator and show you step by step how I achieved that.

Contents

This blog post covers following topics.

Drawable States

In Android, there are 17 different states for the Drawable.

Maybe we don’t even know some of them. I am not going to deep dive into every state. Most of the time, we use pressed, enabled, windows focused, checked etc. If we don’t declare any state for a drawable, this means default state in Android.

We need to understand these states to write our custom StateListDrawable.

StateListDrawable

This is basically a list of drawable items and every item has it’s own state. We create an XML file under res/drawable folder to create StateListDrawable.

This is an item. It has two property. Drawable and State.

This is a StateListDrawable. If we don’t declare any state for an item, as I said before, this means that default state.

Can I use ShapeDrawable?

Yes. Instead of using android:drawable, you can add a custom shape to your item. Here is the item with ShapeDrawable.

You can use StateListDrawable from API level 1. So there is no API level limitation on StateListDrawable.

That’s it. Now our view has state. When user press on it, it’s color will be changed. And user release it, It will have default state and color.

But wait. Clickable? Why did we add that attribute? Should we add that too? Yes. But only for custom views. It takes some time to find out. Buttons work perfectly without adding clickable because it is clickable by default. But If you want to use StateListDrawable for a View, ImageView, Custom View, etc. you need to add clickable attribute.

I added StateListDrawable and here is the commit. It is just like the example I gave above. When user clicks on the layout, layout gets colored. But Let’s make it better with StateListAnimator.

StateListAnimator

Remember when you click on FloatingActionButton and it’s Z value increased with an animation. It is the StateListAnimator behind the scene. Some of the material design widgets have it’s own StateListAnimator internally.

Let’s make it clear with the SO question.

If material design widgets have their own StateListAnimator internally, we can set them null to remove that feature (Don’t recommend it, It is developed for a reason.) And answer sounds more logical right now.

So, how can we create one?

To understand StateListAnimator, we need to understand property animation. I am not going to deep dive into property animation in this blog post. But at least, I want to show you the basics.

Property Animation

Here is the most basic example of the property in an object. X is a property.

The property animation system is a robust framework that allows you to animate almost anything. You can define an animation to change any object property over time, regardless of whether it draws to the screen or not. A property animation changes a property’s (a field in an object) value over a specified length of time.

X is a property. T is a time. In property animation, X is updated in given time. This is basically how property animation works. The box can be a view or any object.

ValueAnimator is a base class for property animation. You can set an update listener to value animator and observe the property changes.

ObjectAnimator is a class that extends from ValueAnimator. You can use ObjectAnimator if you have following conditions;

  • You have an object(Any Class has some property)
  • You don’t want to observe value animator listener
  • You want to update object’s property automatically

So If we have a view (which is an object) and we want to update view’s property (x coordinate, y coordinate, rotation, translation or any property that the view has getter/setter of the property), we can use ObjectAnimator. Let’s continue to create StateListAnimator.

As I said before, we can use object’s property directly without observing changes in animator. every View has translationZ property. So we can directly animate translationZ using ObjectAnimator.

We can also combine multiple s in a . Let’s change another property of the View. Scale X and Scale Y.

Here is the result! Now It is also scaled up when the user pressed. Here is the commit.

You can also define other properties in your animator.xml. Here you can find more information about using ObjectAnimator.

That’s all. I am planning to write something about ValueAnimator and ObjectAnimator. It is a great API animate an object.

Источник

Читайте также:  Как сделать синхронизацию контактов андроид с гугл
Оцените статью