Single activity kotlin android

The SingleFragmentActivity Pattern in Android & Kotlin

Nov 23, 2018 · 5 min read

When I was in college, I did Android programming with a student-run group, as we were a small school in a town of 10,000 folks. It was a great start to working with Android programming, but these were back in the Eclipse days.

Years later I was psyched to see how Kotlin transformed A n droid programming. I first started with a small project, but I found it was much easier to see how Kotlin modernizes a large software system when a good chuck of the project is converted to Kotlin: to get back up to speed, I had to read the Android Programming Guide with Big Nerd Ranch. I haven’t had a chance to read the edition for Kotlin, so if anyone happens to know about it, feel free to comment and compare implementations below! The 2017 print with Java implementations proved to be extremely comprehensive — one of my favorite Android architecture patterns offered in this book is the SingleFragmentActivity pattern. This blurb, we explore how the SingleFragmentActivity pattern enables flexibility across devices in your Android application.

The Android Activity Lifecycle

In Android, Activities were not mean to be flexible. For instance, rotating a screen can make your Activity implementation tricky. When a device is rotated, the instance of the activity possessing the screen is destroyed and re-birthed with a landscape (or portrait) screen view. This means that temporary element states may not be saved unless they’re stuck in the SavedInstanceBundle .

Android Activities are also not flexible in that a layout on an activity is not re-compostable the way Fragments offers compostability at runtime. This is particularly useful for offering better UI experiences by arranging your fragments suited for the device the application is being used on. As a modular and reusable component*, you can share data between fragments and its parent activity within the context of the activity. Even if you’re not sure whether you plan on formatting the look of your fragments differently by device, this implementation is relatively simple and prevents you from boxing yourself in later as your application becomes more complex.

The SingleFragmentActivity pattern involves a Fragment doing all the work while sitting on top of a base Activity. The SingleFragmentActivity pattern is not necessarily the only way to handle and manage UI flexibility and design with ease, but I do like how this pattern creates well-defined roles which can help manage app responsiveness. In the Activity singleton itself, it simply props a Fragment instance with a FrameLayout that composes the UI of the MainActivity . The MainActivity extends SingleFragmentActivity in which the action to create a Fragment creates a new Fragment instance.

Читайте также:  Хороший загрузчик файлов для андроид

The MainActivity class is written in Kotlin, but there isn’t anything that is Kotlin-Android-specific here:

  • override in Kotlin is written on the same line as the function invocation
  • Kotlin is pretty smart about implicit typing. This function invocation could have been equally called override fun createFragment(): Fragment = MainFragment.newInstance() , but this is not necessary since the compiler knows that newInstance() returns a Fragment type at runtime.

The SingleFragmentActivity is significantly more interesting, especially with Kotlin implementations. You might notice that SingleFragmentActivity is an abstract class. In the MainActivity class, we can implement the method createFragment() that we create as an AppCompatActivity type. It’s not required of the inherited class, but in this manner we have created our own super Activity class. With this class, we can guarantee that we won’t spin off unnecessary instances of fragments while using a FragmentManager to handle transactions for fragments. Remember, a FragmentManager handles the lifecycle of all Fragments sitting in a single Activity, so you don’t want to use more than 2–3 Fragments at a time, as the manager will try to keep track of all available Fragments.

SingleFragmentActivity sets the content view to activity_fragment.xml. It then creates a FragmentManager. The FragmentManger locates the fragment container of type FrameLayout. If there are none, then a new Fragment is created and the FrameLayout is added to the fragment.

The SingleFragment Activity is significantly more interesting, especially with Kotlin implementations:

  • Kotlin has a strange-looking snippet for the identifier layoutResId — the way it’s set up, the layout resource id can be accessed like a property.
  • Kotlin Android Extensions allows us to find views by ID without all the boilerplate

Last but not least — where the magic happens (or at least, the app behavior you probably care about). Here, MainFragment inherits your typical onCreate method and onCreateView(. ) for your layout inflation.

This implementation in Kotlin offers some more interesting tidbits for our Android Fragment:

  • You’ll notice the companion object at the bottom of the class. A companion object allows you to call static members without having a class instance but needs access to the internals of a class, which best can be used for reuse or attachment to a particular class instance. Here, we create an instance of MainFragment inherited from the Fragment constructor
  • In Kotlin, you can assign a function to a value with = as opposed to using a lambda block. This can be done if your function has a single assignment
  • For the method onCreateView(…) , but you can only inflate the view there, the views themselves are not available until onViewCreated(…) . The helps guarantee null safety so that you are not tempted to search for View elements until AFTER your Fragment has been inflated and located.
  • In Kotlin, you can refer to the method setRetainInstance(…) as a property, so you can call setRetainInstance = true . When there is a Fragment in an Activity layout, the Activity is recreated it will be searched for again using its id or tag.
Читайте также:  Плеер для android с плейлистами

That’s it for now! Not too bad, right? This implementation will give you something like this:

I’m hoping to cover more tidbits I’ve learned about Android while I was going back to fill in the gaps. Learning Android does take time and patience, but it always helps going back to documentation and source code implementation. Until next time!

Источник

Урок 5. Kotlin. Добавление второго экрана в android-приложение. Передача данных через Intent

Продолжаем курс по обучению основам разработки мобильных приложений в Android Studio на языке Kotlin.

В этом уроке создадим второй экран в приложении, и настроим взаимодействие между экранами с передачей данных.

Предыдущий урок, в котором мы обрабатывали нажатия кнопок, здесь

Продолжаем разработку приложения на языке Kotlin, которое мы делали на прошлом уроке. Исходный код можно скачать на странице прошлого урока.
Пока что наше приложение имеет только один экран. В этом уроке мы добавим второе активити, которое будет отображать экран с данными, полученными на основе данных с первого экрана. При нажатии кнопки Random будет отображаться окно со случайным числом от нуля до текущего значения счетчика.

Вы узнаете

  • Как запустить новое активити с помощью интента
  • Как передать данные во второе активити через интент
  • Как получить данные, переданные через интент во втором активити

Создаем новое активити

  1. Раскройте пакет с именем com.example.android.myfirstapp по пути apps >java >com.example.android.myfirstapp.
  2. Правым кликом выберите команду File >New >Activity >Empty Activity.
  3. В окне настроек нового активити установите для него имя SecondActivity. Убедитесь, что в поле Source Language установлен Kotlin.

Также проверьте им пакета, оно должно соответствовать вашему приложению. Если вы не выделили имя пакета в меню при вызове команды добавления нового активити, установите в это поле android.example.com.myfirstapp.

4. Нажмите Finish. Android Studio создаст файл на языке Kotlin и файл макета на языке XML для нового активити.

5. Дождитесь синхронизации gradle в Android Studio.Gradle это система сборки, которая используется в Android Studio для компиляции и постройки приложения. Вы будете видеть сообщения от gradle о прогрессе сборки приложения внизу экрана.

Изучите файл манифеста

Каждое активити должно быть определено в файле манифеста. Вы можете добавить новое активити в приложение не через меню добавления активити, но тогда вам нужно будет вручную прописать его в манифесте.

Читайте также:  How to connect usb to android

Изучите файл Kotlin нового активити

  1. Откройте файл SecondActivity.kt.
  2. Обратите внимание на метод onCreate(). Постмотрите на вызов setContentView(). Этот метод указывает файл макета activity_second.xml как разметку нового активити.

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

Создаем макет для нового активити

Экран нового активити будет отображать заголовок и случайный номер. На вкладке дизайн редактора макетов можно увидеть, как будет выглядеть экран:


Добавьте TextView для заголовка

  1. Откройте файл activity_second.xml. Вы увидите пустой ConstraintLayout. Это макет по умолчанию для шаблона Empty Activity.
  2. Добавьте TextView из палитры компонентов. Этот TextView будет использовано для отображения заголовка вверху экрана.
  3. Ограничение верхнего края TextView установим по верхней границе окна, левый край по левой стороне, а правый край по правой стороне экрана. Нижний край не ограничиваем.
  4. Установите значение ширину match_parent, а высоту wrap_content, поэтому высота изменится в соответствии с высотой содержимого.
  5. Установите идентификатор @+id/textview_label.
  6. Установите верхний, левый и правый отступ 24dp. Левый и правый отступы могут также иметь значение «start» и «end» для поддержки локализации языков с написанием справа налево.
  7. Установите значение параметра цвета текста @color/colorPrimaryDark и размер текста 24sp.
  8. Поместите текст в TextView «Это случайное число между 0 и %1d.» Спецификатор %1dбудет заменен числом в процессе работы приложения.
  9. Поместите текст в ресурсы с именем random_heading.

Это код XML для TextView, которое отображает заголовок:

Источник

Single activity kotlin android

This is a prototype application tries to serve an example for modularization & clean architecture in Android.

While there are many blogs about good practices, it’s hard to come by a complete example that merges these different popular topics & approaches.

This project takes popular approaches and libraries to create an example on how to actually bind these components with each other.

I’ll soon be writing small series about roadmap, challanges, alternatives and try — fails I’ve encountered during development in Medium.

  • MVVM
  • Databinding
  • Dagger 2
  • Retrofit
  • Moshi
  • Navigation library
  • Coroutines
  • Room
  • Paging
  • Detekt
  • Clean Architecture
  • Modularization
  • JUnit5
  • Mockk
  • Kluent
  • JaCoCo
  • CircleCI
  • Fastlane

Copyright 2019 Melih Aksoy

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

🚀 Example modularized android application with single activity written in Kotlin

Источник

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