- Полный список
- Создание калькулятора чаевых на Kotlin: как это работает?
- Начинаем
- Разработка раздела затрат
- Разработка раздела счетов
- Разработка раздела «Люди и чаевые»
- Добавляем Views
- Доделываем кнопки
- Раздел подсчета затрат
- Финальные шаги
- Let’s learn Kotlin by building Android calculator app
- Why should you want to switch to Kotlin?
- First Kotlin project – simple calculator app
- Kotlin differences and advantages over Java
- Where to learn
- My advice
Полный список
В этом уроке мы:
— пишем приложение — калькулятор
Попробуем написать простейший калькулятор, который берет два числа и проводит с ними операции сложения, вычитания, умножения или деления. Результат отображает в виде полного выражения.
Project name: P0191_SimpleCalculator
Build Target: Android 2.3.3
Application name: SimpleCalculator
Package name: ru.startandroid.develop.simplecalculator
Create Activity: MainActivity
Откроем main.xml и нарисуем экран:
Тут есть два поля ввода, 4 кнопки и текстовое поле для вывода. Обратите внимание на атрибут inputType для EditText. Он задает тип содержимого. Я указал numberDecimal – т.е. в поле получится ввести только цифры и запятую, буквы он не пропустит. Это удобно, не надо самому кодить различные проверки.
Для TextView указан атрибут gravity. Он указывает, как будет расположен текст в TextView. Не путайте с layout_gravity, который отвечает за размещение TextView в ViewGroup.
Теперь нам надо читать содержимое полей, определять какую кнопку нажали и выводить нужный результат. Открываем MainActivity.java и пишем код
Думаю, все понятно по каментам. Читаем значения, определяем кнопку, выполняем операцию и выводим в текстовое поле. Обработчиком нажатий на кнопки выступает Activity.
Все сохраним и запустим.
Давайте для большего функционала сделаем меню с пунктами очистки полей и выхода из приложения. Пункты будут называться Reset и Quit.
Добавим две константы – это будут ID пунктов меню.
(добавляете только строки 3 и 4)
И напишем код создания и обработки меню:
Сохраним все, запустим. Появилось два пункта меню:
Reset – очищает все поля
Quit – закрывает приложение
В качестве самостоятельной работы вы можете реализовать проверку деления на ноль. И выводить какое-нить сообщение с помощью Toast или прямо в поле результата.
На следующем уроке:
— рассмотрим анимацию View-компонентов
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Создание калькулятора чаевых на Kotlin: как это работает?
Рассказываем, как создать простое приложение для расчета чаевых на языке Kotlin. Если точнее, то Kotlin 1.3.21, Android 4, Android Studio 3. Статья будет интересной, в первую очередь, для тех, кто начинает свой путь в разработке Android-приложений. Она позволяет понять, что и как работает внутри приложения.
Такой калькулятор пригодится, когда нужно подсчитать сумму чаевых с компании, решившей провести время в ресторане или кафе. Конечно, не все и не всегда оставляют официантам на чай, это больше западная традиция, но процесс разработки такого приложения в любом случае интересен.
Напоминаем: для всех читателей «Хабра» — скидка 10 000 рублей при записи на любой курс Skillbox по промокоду «Хабр».
Вот как выглядит приложение в процессе работы:
Вы вводите желаемый процент с общей суммы, количество участников встречи и получаете результат — сумму чаевых, которые стоит оставить.
Начинаем
Полный интерфейс приложения выглядит следующим образом:
Первое действие — загрузка основы проекта. Открываем ее в Android Studio 3.0 или более поздней версии. Строим и запускаем проект и видим белый экран. Все нормально, так и должно быть.
Действия пользователя прописаны в проекте в хронологическом порядке, чтобы все было понятно. Для его просмотра открываем View -> Tool Windows -> TODO.
Изучаем проект и открываем colors.xml для оценки цветовой палитры. В strings.xml размещены текстовые данные (подписи), а в styles.xml есть несколько шрифтовых шаблонов.
Разработка раздела затрат
Открываем activity_main.xml и добавляем расположенный ниже код в LinearLayout (#1):
Теперь можно настроить стиль директории values или поиграть с цветами, используя инструмент material.io.
Сейчас проект выглядит так:
Как видите, расчет затрат производится по данным, которые вносит пользователь.
Разработка раздела счетов
Добавляем код, размещенный ниже, в LinearLayout после Expense Section (#2):
Закрываем LinearLayout после списка TODOs, а затем добавляем новый код, размещая его внутри LinearLayout (#3):
Поскольку главная задача приложения — расчет индивидуальных затрат для каждого из участников посиделок в ресторане, то основное значение играет costPerPersonTextView.
EditText ограничивает ввод данных одной строкой, у этого параметра должно быть значение NumberDecimal inputType.
Запускаем проект для теста и вводим параметры общего ущерба (разбитые чашки, тарелки и т.п.)
Разработка раздела «Люди и чаевые»
Чтобы добавить выбора объема чаевых, вставляем расположенный ниже код в новую секцию LinearLayout (#4):
Этот участок кода необходим для точного расчета суммы чаевых. Дефолтное значение текста — 20. ImageButtons снабжены иконками в папке с правами записи.
Полностью копируем раздел и добавляем следующее (#5):
- ImageButton ids (subtractPeopleButton, addPeopleButton)
- TextView ids (numberOfPeopleStaticText, numberOfPeopleTextView)
- DefaultText для numberOfPeopleTextView (должен быть 4).
Теперь при запуске приложения есть возможность добавить сумму счета, также работают кнопки «Добавить/Вычесть», но пока ничего не происходит.
Добавляем Views
Открываем MainActivity.kt и добавляем вот это в функцию initViews (#6):
Доделываем кнопки
Чтобы добавить поддержку клика кнопок, внедряем View.OnClickListener на уровне класса (#7):
Скомпилировать проект прямо сейчас не выйдет, нужно выполнить еще несколько действий (#8):
В плане кнопок и свитчей у Kotlin все организовано очень круто! Добавляем размещенный ниже код во все функции increment и decrement
Здесь код защищает функции приращения с максимальными значениями (MAX_TIP & MAX_PEOPLE). Кроме того, код защищает функции декремента с минимальными значениями (MIN_TIP & MIN_PEOPLE).
Теперь связываем кнопки со слушателями в функции initViews (#13):
Теперь можно добавлять общий ущерб, чаевые и количество участников встречи. Ну и теперь самое главное…
Раздел подсчета затрат
Этот код подсчитывает затраты (#14):
Ну а здесь вызывается функция, которая дает возможность учесть количество людей в компании и подсчитать чаевые (#15):
Запускаем приложение. Выглядит и работает оно отлично. Но может быть и лучше.
Если вы попытаетесь удалить сумму счета, а затем увеличить число подсказок или друзей, приложение упадет, поскольку еще нет проверки для нулевого значения затрат. Более того, если вы попытаетесь изменить сумму счета, расходы не будут обновлены.
Финальные шаги
Добавляем TextWatcher (#16):
Затем встраиваем слушатель billEditText (#17):
Плюс добавляем код для выполнения TextWatcher (#18):
Ну а теперь работает абсолютно все! Поздравляю, вы написали собственный «Калькулятор чаевых» на Kotlin.
Источник
Let’s learn Kotlin by building Android calculator app
One of the biggest news of Android world in 2017 definitely became Kotlin. This is new programming language from JetBrains which has been announced as official Android development language during Google I/O 2017 event. So there are no more excuses to make for not learning it. In this post I will share my findings on Kotlin and show you how to build small Android calculator app using this new language.
Why should you want to switch to Kotlin?
But first lets talk about any questions or doubts that could developer have to start using Kotlin. I won’t lie, I had all these myself, but after some research managed to find all the answers. Main question for me was why the hell do we need Kotlin when we have already reliable and one of the most popular language in the world Java? Answer here is so predictable. We all know that Java is already old language which is not changing a lot and fast enough, so it don’t have modern programming language features compared to other languages. Meanwhile Kotlin is really modern, with it you can write more safer and more functional code which besides being shorter manages to do more than written in Java. It is is designed with the idea to be just a better language than Java. Sounds good? Another question that comes to my mind is if Kotlin is already finished language, can we trust it to use in real life projects? You know sometimes to rush and chase the latest technology is not the best idea while it’s just half-baked. However Kotlin language first appeared on 2011. First stable Kotlin version was released only on 2016, so as you see it was developed for really long time until matured to reliable complete language. Finally I bet you would like to know how easy is to start using Kotlin in your Android projects? After trying myself I was really surprised to find out how many effort is made to have as easy transition from Java as possible. Most amazed I was with the fantastic feature inside Android Studio, our daily IDE used for Android development work, to convert from Java to Kotlin code automatically. If you are new to Kotlin this will be really helpful during your first steps while you get used to the language. Besides Kotlin is fully interoperable with Java code, which means that you can create mixed projects with both Kotlin and Java files coexisting. So you can start gradual migration from Java to Kotlin with your projects. Also please think about the idea that you can confidently expect best compatibility for Kotlin language with Android Studio and always up to date support. Why? Because Kotlin is designed by JetBrains, company known for creating IntelliJ IDEA, a powerful IDE for Java development. And Android Studio is based on IntelliJ. Moreover Google announced first-class support for Kotlin on Android, which means all their libraries, frameworks, features should work smoothly with the new language.
First Kotlin project – simple calculator app
Ok do you recognized my idea of importance to switch from Java to Koltin as soon as possible? Are you already motivated to try Kotlin building real app? For my first experiments with Kotlin I decided to go with the plan of creating simple calculator app. It’s one of my most often used applications whether it would be a personal computer or mobile phone. Actually between all these different platforms that I use, my favorite representation of calculator is on Windows 10. What I like in it that it shows nicely your recent actions and then stores your history.
So I decided to recreate it’s standard version on Android using Kotlin with all these my mentioned features included, which became more challenging than I thought at first time, but after all I reached nice result that I share with you.
You can dive to the code directly on GitHub to check it out how it was done.
Kotlin differences and advantages over Java
Kotlin language comes with many differences and advantages over Java that you will notice. Let’s have a look to some of them that I have faced immediately while working on my calculator app project:
- We don’t use semi-colons at the end of the sentences anymore. This is simple one and the first thing I noticed instantly. 😉 Also it is recommended practice by IDE which warns about that.
- When extending a class or implementing interface, you replace Java’s extends or implements with a colon, and then attach the name of the parent class or interface. Also classes are final by default, and can be extended only if it’s explicitly declared as open or abstract.
- In Kotlin defining parameters is vice versa to Java. Here first we write the name and then its type.
- Variables defined by two different keywords var which means variable value can be changed and val which means that value cannot be changed. Also compiler is smart enough to recognize type of variable without declaring it as Kotlin is a strongly typed language that supports type inference.
- Functions are defined using the fun keyword instead of void . Function’s name comes before its type, which is opposite to Java.
- Kotlin is null safe. You decide whether an object can be null or not by using the safe call operator – question mark. By default it cannot. We avoid a lot of defensive code which we used in Java just to check whether something is null before using it just to avoid unexpected NullPointerException .
- Has lambda expressions which allows reducing the amount of code needed to perform some tasks. The common example is adding a click listener to a button with one line instead of multiple lines in Java.
button1.setOnClickListener - Newly introduced property modifier lateinit identifies that the property should have a non-nullable value and its assignment will be delayed. This is very handy when we need something else to initialize a property, but we don’t have the required state available in the constructor or no access at that moment.
- Meanwhile also new keyword lazy means that your variable should not be initialized unless you use that variable in your code. Have in mind that it would be initialized only once and after that always the same value used.
- Kotlin has extension functions and properties. This adds new functionality or properties to a class even we don’t have access to modify the source code of that class. So if you ever wished that a class should have a function or a property that was not available, now you are free to create one. This is such a nice feature clearly showing that it is a modern programming language. 🙂
- Statement if..else is also as an expression in Kotlin as it has the ability to assign a variable from the returned value of the statement.
- As a replacement for the familiar switch statement Kotlin offers new expression when which has more powerful features and is more concise.
- Kotlin has string templates.
- Kotlin doesn’t have checked exceptions but instead all exceptions are unchecked. That’s the main difference between Kotlin and Java exception mechanisms. Exceptions are not explicitly declared in the function signatures, as they are in Java. If we feel that exception might arise even if it is not enforced by the Kotlin compiler, we should handle it by surrounding the method with with a try. catch block. Useful annotation called @Throws in Kotlin might come in handy when you still want to add the possible exceptions that might be thrown to a method signature.
Where to learn
Here I pointed out just a few things, but there are so much more new features in Kotlin that makes this language different from Java and really modern one. To find out all of them and to learn Kotlin in general I would like to recommend amazing book which I have read myself – “Kotlin for Android Developers” by Antonio Leiva. If you feel that reading a book is too slow and too boring for you than any online course could be best alternative. You could try one from my favorite provider Pluralsight called “Kotlin Fundamentals” by Kevin Jones. After watching it I found out this to be made really professional with deep language coverage, and also as a great addition to reading a book.
My advice
I hope you will find this small Android calculator app code useful while exploring various Koltin language projects over internet. But remember that really to learn new language you need to start building something by your own. Happy learning and coding in Kotlin! Don’t forget to share your projects too.
This post was also republished on Medium. Show your support by clicking the clap button 👏 on the story page here. 😇🙏
Источник