- ScaleAnimation и
- Пульсация
- res/anim/enlarge.xml
- res/anim/shrink.xml
- Упрощаем код
- Атрибуты fillBefore, fillAfter и fillEnabled
- Упругая кнопка
- Класс ScaleAnimation
- Орёл или решка
- Через XML
- shrink.xml
- grow.xml
- Полный список
- Level List
- Transition Drawable
- Inset Drawable
- Clip Drawable
- Scale Drawable
- Animation drawable
- How to scale android
- About
ScaleAnimation и
Тег scale и соответствующий ему класс ScaleAnimation служат для анимации размеров объекта.
Пульсация
Используйте атрибуты scaleHeight и scaleWidth внутри тега , чтобы описать высоту и ширину относительно границ оригинального объекта Drawable. Используйте атрибут scaleGravity для изменения опорной точки масштабированного изображения.
Рассмотрим пример масштабирования. Создадим проект, в котором элемент ImageView будет пульсировать — постоянно увеличиваться и уменьшаться в размерах. В папке res/anim создадим два файла:
res/anim/enlarge.xml
res/anim/shrink.xml
Разместите в макете активности компонент ImageView и добавьте код:
Запускайте проект и любуйтесь эффектом.
Ваш браузер устарел. Видео не увидите
Упрощаем код
На самом деле мы написали очень много лишнего кода. Если посмотреть внимательно на созданные нами файлы анимации, то увидим, что они содержат одинаковые параметры, которые меняются в обратном порядке — размеры увеличиваются или уменьшаются. Для подобных случаев, когда используются одинаковые значения для анимации, предусмотрены атрибуты repeatMode и repeatCount. Первый атрибут позволяет сменить направление анимации, а второй — задаёт число анимаций (infinite для бесконечности или любое число больше нуля).
Упростим код предыдущего примера. Удалим файл shrink.xml. В файле enlarge.xml добавим пару новых атрибутов:
В коде нам уже не понадобятся слушатели анимаций и загрузка второго файла анимации. Код станет намного короче. Судите сами:
Атрибуты fillBefore, fillAfter и fillEnabled
Возможно, в некоторых примерах вам будут попадаться атрибуты анимации fillBefore, fillAfter fillEnabled или их программные аналоги — методы setFillAfter(), setFillBefore(), setFillEnabled().
С помощью данных атрибутов можно указать, когда следует проводить трансформацию. Так fillAfter показывает, что финальная трансформация происходит после окончания анимации, а fillBefore показывает, что начальная трансформация происходит до начала анимации.
Это может быть полезным в некоторых случаях. Как это работает, лучше смотреть на живых примерах.
Также применимо к набору анимаций:
Упругая кнопка
Ещё один пример создания эффекта упругой кнопки. Для этого к анимации следует добавить Interpolator.
Добавим в центр экрана кнопку.
В папке res/anim создадим файл bounce.xml для анимации кнопки — будем увеличивать её размер.
На этом этапе можно запустить простую анимацию по щелчку.
Не слишком эффектно. Добавим интерполятор. Создадим новый класс.
Добавим в анимацию.
Ваш браузер устарел. Видео не увидите
Класс ScaleAnimation
Класс ScaleAnimation наследуется от класса Animation и отвечает за анимацию изменения размеров.
Орёл или решка
Напишем пример анимации flip — переворачивания изображения на другую сторону.
Добавим на экран ImageView, который будет содержать одну из сторон монеты.
Напишем код переворачивания монетки:
Сжатие происходит с полного размера до 0 от краёв к центру. Расширение использует обратный процесс.
Запустив проект, мы можем наблюдать распространённый эффект вращения монеты (flip), когда видим обратную сторону. Для круглых изображений эффект выглядит достаточно приемлемо. Для прямоугольных изображений лучше использовать анимацию при помощи ObjectAnimator, который использует перспективу для более реалистичного эффекта.
Через XML
Чтобы воспроизвести этот же эффект через XML, создадим два файла в папке res/anim:
shrink.xml
grow.xml
Разметку оставим прежней, только напишем другой код:
На скриншоте представлены две стороны монеты. Если у вас есть такая монета, то свяжитесь со мной. Я хочу такую монету.
Источник
Полный список
Продолжаем разбирать типы Drawable, которые можно описывать с помощью XML-разметки. Проектов в этом уроке создавать не будем. Я просто буду в своем проекте создавать XML-файлы в папке drawable и ставить их фоном для View. А в тексте урока приведу код и скрины. Иногда буду вешать дополнительно серый фон, чтобы был виден реальный размер View.
Чтобы программно добраться до Drawable, который вы для View повесили как фон, надо просто вызвать метод getBackground.
Level List
Тег позволяет отображать Drawable в зависимости от значения level. Рассмотрим пример, где будем отображать три разных Drawable: если level=0, то зеленый прямогуольник; если 1, то желтый; если 2, то красный. Создадим три Drawable
Level List, в котором мы указываем какой Drawable при каком максимальном уровне (maxLevel) отображать.
Менять уровень у Drawable мы можем методом setLevel. Ставим 0 (по умолчанию)
В соответствии с заданным уровнем отображается Drawable.
Кроме атрибута maxLevel можно также использовать атрибут minLevel для указания минимального значения.
Transition Drawable
XML выглядит так:
Также у item есть атрибуты left, top, right, bottom для задания отступа.
В коде, для переключения между Drawable используются методы startTransition и reverseTransition. Оба метода принимают на вход количество мсек, которое будет длиться переход.
Inset Drawable
Насколько я понял – это просто обертка Drawable, которая позволяет указать padding-отступы. Корневой тег – , атрибуты отступа insetLeft, insetTop, insetRight, insetBottom.
Clip Drawable
Тег позволяет обрезать Drawable по горизонтальной и (или) вертикальной оси. Какая часть картинки будет обрезана зависит от значения level. Используемый диапазон тут от 0 до 10000, где 0 — картинка полностью обрезана и не видна, 10000 — картинка видна полностью. Атрибут gravity позволяет указать направление урезания.
Рассмотрим несколько примеров.
Устанавливаем программно (методом setLevel) уровень в 7000. А XML рисуем такой:
Ось — горизонтальная, направление — влево. Т.е. картинка обрезается по горизонтали справа-налево до 70% (7000 от 10000).
Уровень установим в 2000, а xml делаем таким:
Картинка обрезается по вертикали снизу вверх до 20%
Уровень 5000, xml:
Картинка обрезается по обоим осям вправо и вниз до 50%
Уровень 6000, xml:
Картинка обрезается по горизонтали к центру до 60%
Scale Drawable
Тег позволяет сжать картинку по горизонтальной (scaleWidth) и (или) вертикальной (scaleHeight) оси и сместить полученное изображение в указанную часть (scaleGravity) доступного пространства.
У меня этот тип Drawable работал только, если установить ему level > 0.
Сжимаем на 30% по горизонтали и смещаем влево.
Сжимаем на 70% по вертикали и смещаем вниз.
Сжимаем на 50% по обоим сторонам и смещаем вправо-вниз.
Сжимаем на 40% по ширине и 60% по высоте, и смещаем в центр
Animation drawable
Список Drawable с указанием времени отображения для каждого. Атрибут oneShot установленный в true говорит системе о том, что воспроизведение нужно только один раз. Если поставить false, то анимация будет циклично повторяться.
Чтобы запустить процесс анимации, необходимо получить Drawable, привести его к типу AnimationDrawable и вызвать метод start.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
How to scale android
Scala Android Tutorial
Step by Step walk through for programmers wanting to use Scala for android development
Scala has started to become my personal favorite language, however it is a very difficult language for beginners and it is very hard to find how to set up your development environment, especially for setting it up for use with android. This guide will go step by step on how to set up Scala for use with android. This is intended to be an easy guide even for complete beginners to Scala and it will cover all steps. I find some steps in tutorials that others may skip because they think it is obvious to sometimes cause the worst setup issues. You should have prior java experience and a decent understand of how android works and some Scala knowledge is recommend, but other than that, anyone should be able to jump in to use Scala for android.
I do focus on OSX in this tutorial, however if you are using linux, you will be able to follow along.
*Note: This tutorial focuses on creating a new project. Instructions for cloning into an existing project are found here.
Installation
Android specific steps
Step 1: Install java from oracle. Currently Kit-Kat supports java 7, but it is recommend to download java jdk 7 and 6.
Step 2: Install Android. You can use a package manager such as brew or go to here. If you downloaded Android from the website, you will need to set the path in your
/.bash_profile . Also, you should set the ANDROID_HOME environment variable to the path to your sdk.
Step 3: Type android into the command line and it will open a list of packages. Make sure to download and install the tools package as well as the api you wish to use.
Step 4: (Recommended) Install Intellij for development. You can use the command line, but especially with scala Intellij is the best for android development. Other plugins for eclipse and android studio are less developed and Intellij should be used if you want to use an IDE over the command line.
Scala specific steps
Step 5: Install Scala. You can use brew install Scala or another package manager or simply download from http://www.scala-lang.org. If you download it manually, you will again need to set the path in your
/.bash_profile file to /path/to/scala/scala_version/bin . Verify Scala works by typing source
/.bash_profile and then typing Scala into the terminal. If it pulls up the Scala interpreter, it is successfully installed.
Step 6: Install SBT. Using Scala with android is best when you use SBT to build your projects instead of traditional Android methods. SBT stands for simple build tool and is used for most Scala projects. You can either brew install SBT or download sbt from the SBT website. Again, if you install SBT manually, you need to set your path in your profile. Verify it works by sourcing your profile and typing sbt into the command line.
Creating the Project
*Note: Here i will walk through the intelij setup of the project mostly. Setting up from the command line will be relatively straightforward however and still should follow the flow as used in Intellij.
Step 1: Create the android project. Use android create project, build your own or the best option is to create it from within Intellij itself. If within Intellij, choose Application module within Android and name your application, give it a package name, and create a hello world activity that will be your main activity upon launch. Next, set the project location on your local machine and set the Project SDK to the location of your android environment (Note: if you used brew, this will likely be at /usr/local/Cellar/android-sdk ). It should then show Android API 19(or whatever version of Android you are using).
Now we will make the project an SBT project
Step 2: First, create a new folder called project in the root directory of the project, i.e. myapp/ from either the command line or from intellij.
Step 3: Cd into the project folder and create a file called build.properties and another file called plugins.sbt
Step 4: In the build.properties, ‘type sbt.version=0.13.0’ (or whatever version of sbt you are using)
Step 5: In plugins.sbt, add this:
The first plugin allows for android to function with the SBT build. The second plugin allows for integration within intellij so you can build projects from within the IDE.
Step 6: Cd back to the root directory of the project and create a file called build.sbt. Within it put:
This file specifies the Scala version you are using, android target, compiling options and it also allows the scaloid framework to be integrated into the SBT build. Essentially this file is used for specifying the build settings for SBT when building the Scala Android project.
Step 7: From the command line and in the root directory, type sbt. All the project dependencies will be fetched and downloaded.
Step 8: You now can type several commands in SBT
- compile
- android:package-release (creates the release apk)
- android:package-debug (creates the debug apk which is used for development)
- android:package (builds the sbt project and runs the app)
Run compile , android:package-release , and android:package-dubug
Step 9: Next type gen-idea (still within sbt). This will allow the project files to be generated for intellij.
Step 10: Install the intellij SBT and Scala plugins. Go to Preferences > Plugins and click install JetBrains plugin. Scala and install it. Download the SBT plugin from a seperate web browser and from plugins setting page, install the downloaded plugin from disk and find the location of where you downloaded the file, apply the changes, then reload Intellij.
Step 11: Change the Intellij build process. Click on Run > Edit Configurations. If you need to, create a new configuration using the + in the top left corner and specify it as and Android Application. Set the module to myproj and specify the default launch activity. Then at the bottom where it says before launch, remove make and instead click on the plus and choose the SBT option. A window will pop up asking you specify the sbt command. Here type in android:package . After you hit enter, it should say in the before launch window Run SBT Action ‘android:package’ . Apply the changes and hit ok.
Step 12: Go to your src folder and find your package that you created. Find the main activity (mine is MyActivity) and delete the java file. Create a new scala file in that same package with the same name as the java File.
Step 13: If you are wanting to use scaloid, your file may look like this. You may also design a traditional xml based file in the res folder and structure the Scala code around that but I personally find Scaloid easy to use and it works well.
Step 14: Run the app.
Step 15: Add more activities. Just to show you how Java and Scala can run together, I will add both a java activity and a Scala activity that can easily transition between each other.
Add this to the Main Activity
Create another Scala activity and make it look like this:
Create a Java class and an XML layout file in the res/layout/ folder called javaxml
Make sure to edit your AndroidManifest.xml file and add the following underneath the main activity
Step 16: Run the project again and you can see how seamless it is to transition from a Java class to a Scala class and vice versa.
Step 17: Add your .gitignore file and push your repository. Your .gitignore should look like this:
Step 18: If you are working on a team and you need to know how to set up the project for other members, instructions are found here.
About
Step by Step walk through for programmers wanting to use Scala for android development
Источник