Text change animation android

Android TextView Animation – Animate Text Change in TextView

Hi and welcome to another tutorial from Codingdemos, today you will learn about Android TextView animation and how you can animate text changes inside TextView.

By the end of this tutorial, you will have an app that looks like this. (Large preview)

You will be using a 3rd party library called FadingTextView to help you make this smooth TextView animation.

In this tutorial we will be using the following:

    – Android studio version 3.0.1
    – Android emulator Nexus 5X with API 26
    – Minimum SDK API 16

1- Open up Android Studio and open any project that you have in your computer.

Create new Android Studio project or open existing project. (Large preview)

2- Open up build.gradle (module:app) and add the library in the dependencies.

3- Next you need to open up build.gradle (Project) and add Jcenter because this library is available through it.

4- Now sync your project by clicking on Sync Now.

5- Open up colors.xml file to change the colors of the main app.

6- Build and run the app to see the new colors.

7- Open strings.xml file and add a string array.

You will be using this string array later with FadingTextView to show text animation.

8- Open up activity_main.xml file and add FadingTextView.

Here you are using app:texts to reference the string array which you have created earlier so that it appears inside FadingTextView, then you use app:timeout which represent the amount of time in milliseconds that each text is visible.

9- Build and run the app to see the output.

10- Let’s customize the layout to include other TextViews as well like this.

11- Build and run the app to see the result.

FadingTextView with other TextViews. (Large preview)

12- Now let’s customize the appearance of FadingTextView by increasing text size, changing the text color, make it bold as well as add some margin from top and bottom.

13- Build and run the app to see the result.

Now you can see Android text animation effect. (Large preview)

14- Here is the full code for activity_main.xml file.

15- I hope you find this tutorial helpful and if you have any question please post them in the comment below.

Источник

How to make text fade in and out in Android?

I have a paragraph of text and when a button is clicked I want that text to fade out, change to some other text, then fade back in. I have some code but it doesn’t do the fade out animation just the fade in.

6 Answers 6

You seem to be setting the animation to in right after you had set it to out. This makes only the «in» animation work.

Читайте также:  Как скомпилировать python для android

To make the second animation start right after the first, you can add a listener to your first animation:

Then, in your onClick() method:

That should do the trick.

Another approach is to use AnimationSet .

Then, instead of starting out , start as .

I hope this helps!

You should consider using something like a TextSwitcher . There is a brief document on TextSwitcher in the Android documentation. What I would recommend best though is to look at the API Demos, there is a great and simple to use one of TextSwitcher s. Download the API Demos and check them out for yourself, or see here.

If you want to use Animation , you can use an AnimatorListener to listen for when the first animation is done, and then start the second animation. That would be onAnimationEnd() .

There might be a better way to do it with AnimationSet , but this works for sure.

There is a better way to make the same effect.

You should configure the animation to repeat in the inverse mode.

Here is an example:

to add to eboix answer. this is how I fade in text and fade out text, with delay between each fade and before fade out, (i.e right after fade in).

My XML looks like this.

The you use this variables in in your activity/fragment/dialogfragment, the following are the variables I used in mine.

Now the objects and variables are innitialized are used like this, I used this for my dialog fragment, in the oncreateDialog method..

Источник

Text color animation

Is there a way to animate a text color change (from anycolor to white)?

The only variant I came up with, is placing two textviews (with the same text) in one place, and fading the top one, so the bottom one (that has a white color) will become visible.

P.S. I scrapped the variant of the 2 TextViews since it looked weird (edges weren’t smooth and, since I have a lot of such elements on the screen it was really lagging the scrolling). What I did, was a crazy hack that does the animation with the use of a Thread and setTextColor (that also forces redraw of a textview).

Since I needed only 2 color changes (from red to white, and from green to white) I hardcoded the values and all of the transition colors between them. So here’s how it looks:

8 Answers 8

You can use new Property Animation Api for color animation:

For backward compatability with Android 2.x use Nine Old Androids library from Jake Wharton.

The Easiest solution will be to use Object Animators :

No need to keep handles to the two text views. First add the fadeIn/fadeOut animations:

Just implemented it like this so proven to work.

best way use ValueAnimator and ColorUtils.blendARGB

Although I haven’t found a totally distinct method, I have tried to use a TextSwitcher (with the fade animation) to create the colour-change effect. A TextSwitcher is a kind of ViewSwitcher which literally animates between two (internal) TextView s. Did you manually implement the same system unknowingly? 😉 It manages a bit more of the process for you, so you may find it easier to work with (especially if you want to try more involved animations). I would create new subclass of TextSwitcher and some methods e.g. setColour() which can set the new colour and then trigger an animation. The animation code can then be moved outside of your main application.

  • make sure you keep a handle on the two TextView s that are put into the switcher
  • change the colour of the other TextView and call setText() to animate between them
Читайте также:  Все самое новое для андроид смартфонов

If you are already using a ViewSwitcher then I don’t think there is an easier way to implement this.

Источник

Полный список

В этом уроке мы:

— рассмотрим анимацию View-компонентов

Перед серьезными темами я решил все таки рассмотреть еще одну интересную и, на мой взгляд, несложную тему. Правда рассмотрю я только вершину и в дебри не полезу. Тема – анимация. Мы научимся проделывать следующие трансформации с обычными View-компонентами:
— менять прозрачность
— менять размер
— перемещать
— поворачивать

Создадим проект:

Project name: P0201_SimpleAnimation
Build Target: Android 2.3.3
Application name: SimpleAnimation
Package name: ru.startandroid.develop.p0201simpleanimation
Create Activity: MainActivity

Трансформации конфигурируются в XML файлах, затем в коде программы считываются и присваиваются View-элементам. Я не буду дублировать хелп и все расписывать, а сразу перейду к практике.

В нашем проекте есть папка res. Надо в ней создать папку anim. Сделать это можно, например, так: правой кнопкой на res и в меню выбираем New -> Folder. В папке anim надо создать файлы. Делается это аналогично: правой кнопкой на anim и в меню выбираем New -> File. В этих файлах будем конфигурировать анимацию.

Создаем следующие файлы в папке res/anim:

Имя файла: myalpha.xml

Описание трансформации: меняется прозрачность с 0 до 1 в течение трех секунд.

Имя файла: myscale.xml

Описание трансформации: изменение размера с 0.1 от оригинальной ширины и высоты до 1. Точка, относительно которой будет производиться масштабирование, лежит ровно посередине объекта (pivotX, pivotY). Продолжительность – 3 сек.

Имя файла: mytrans.xml

Описание трансформации: перемещение с -150 относительно текущей позиции по оси X и -200 по оси Y в текущую позицию (0,0). Продолжительность – 3 сек.

Имя файла: myrotate.xml

Описание трансформации: поворот относительно левого верхнего угла (т.к. не указаны pivotX, pivotY) на 360 градусов в течение трех секунд

Имя файла: mycombo.xml

Описание трансформации: одновременно увеличение размера и вращение в течение трех секунд. Обратите внимание, для комбинации трансформ использован тег

Итак, мы создали 5 файлов анимации.

И теперь можем применять их к View-компонентам.

Открываем main.xml и создадим экран:

По центру экрана находится TextView, к нему и будем применять трансформации. Для этого создадим контекстное меню для TextView, добавим пункты меню, соответствующие нашим наборам и при нажатии будем запускать анимацию.

Анимация читается из xml-файла методом AnimationUtils.loadAnimation, на выходе получается объект типа Animation. Его используем в методе startAnimation, который запускает анимацию.

Все сохраним и запустим приложение. Вызываем контекстное меню для TextView, и тестируем анимации

Читайте также:  Эффект пленки для андроид

Я использовал не все возможности и параметры. Есть еще, например, параметр android:startOffset – он указывает задержку при старте анимации. Т.е. если указать android:startOffset=”1000”, то анимация начнется через секунду. Это удобно использовать если вы делаете набор трансформ ( ) и вам надо чтобы они запускались не одновременно, а в определенном порядке. Также полезный параметр android:repeatCount – это количество повторов.

Рекомендую поиграть параметрами в XML файлах и посмотреть, что получается.

На следующем уроке:

— создаем в приложении второй экран

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

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

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

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

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

Источник

How to make text fade in and out in Android?

I have a paragraph of text and when a button is clicked I want that text to fade out, change to some other text, then fade back in. I have some code but it doesn’t do the fade out animation just the fade in.

6 Answers 6

You seem to be setting the animation to in right after you had set it to out. This makes only the «in» animation work.

To make the second animation start right after the first, you can add a listener to your first animation:

Then, in your onClick() method:

That should do the trick.

Another approach is to use AnimationSet .

Then, instead of starting out , start as .

I hope this helps!

You should consider using something like a TextSwitcher . There is a brief document on TextSwitcher in the Android documentation. What I would recommend best though is to look at the API Demos, there is a great and simple to use one of TextSwitcher s. Download the API Demos and check them out for yourself, or see here.

If you want to use Animation , you can use an AnimatorListener to listen for when the first animation is done, and then start the second animation. That would be onAnimationEnd() .

There might be a better way to do it with AnimationSet , but this works for sure.

There is a better way to make the same effect.

You should configure the animation to repeat in the inverse mode.

Here is an example:

to add to eboix answer. this is how I fade in text and fade out text, with delay between each fade and before fade out, (i.e right after fade in).

My XML looks like this.

The you use this variables in in your activity/fragment/dialogfragment, the following are the variables I used in mine.

Now the objects and variables are innitialized are used like this, I used this for my dialog fragment, in the oncreateDialog method..

Источник

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