Kotlin 27

When to use function vs property in Swift

Issue #687

Although I do Swift, I often follow Kotlin guideline https://kotlinlang.org/docs/reference/coding-conventions.html#functions-vs-properties

In some cases functions with no arguments might be interchangeable with read-only properties. …

How to use synthetic property in Kotlin Android Extension

Issue #555

Synthetic properties generated by Kotlin Android Extensions plugin needs a view for Fragment/Activity to be set before hand.

In your case, for Fragment, you need to use view.btn_K in onViewCreated

override fun onCreateView(inflater: …

How to access view in fragment in Kotlin

Issue #497

Synthetic properties generated by Kotlin Android Extensions plugin needs a view for Fragment/Activity to be set before hand.

In your case, for Fragment, you need to use view.btn_K in onViewCreated

override fun onCreateView(inflater: …

How to add AdMob to Android app

Issue #431

Use AdMob with Firebase

build.gradle

buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath …

How to use flow in Kotlin

Issue #388

Asynchronous Flow

https://kotlinlang.org/docs/reference/coroutines/flow.html

Using List result type we can only return all the values at once. To represent the stream of values that are being asynchronously computed we can use Flow type …

How to create bounce animation programmatically in Android

Issue #383

Right click res -> New -> Android Resource Directory, select anim and name it anim Right click res/anim -> New -> Android Resource file, name it bounce

<?xml version="1.0" encoding="utf-8"?>
<set …

How to use point in dp programmatically in Android

Issue #382

import android.content.Context

fun Int.toDp(context: Context?): Int {
    if (context != null) {
        val scale = context.resources.displayMetrics.density
        return (this.toFloat() * scale + 0.5f).toInt()
    } else { …

How to create constraints programmatically with ConstraintLayout in Android

Issue #381

From API < 17, there is ViewCompat.generateViewId() For API 17, there is View.generateViewId()

Note that to use ConstraintSet, all views under ConstraintLayout inside xml must have unique id

val imageView = ImageView(context)
imageView. …

How to use custom font as resource in Android

Issue #380

Downloadable fonts

https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts

Android 8.0 (API level 26) and Android Support Library 26 introduce support for APIs to request fonts from a provider application instead of …

How to get Hacker News top stories using parallel coroutine and Retrofit

Issue #379

interface Api {
    @GET("topstories.json?print=pretty")
    suspend fun getTopStories(): List<Int>

    @GET("item/{id}.json?print=pretty")
    suspend fun getStory(@Path("id") id: Int): Item
}
class Repo { …

How to show generic list in Fragment in Android

Issue #378

After having a generic RecyclerView, if we want to show multiple kinds of data in Fragment, we can use generic.

We may be tempted to use interface or protocol, but should prefer generic.

class FeedFragment() : Fragment() {
    override fun …

How to use Product Hunt GraphQL API with Retrofit

Issue #370

Define response model

import com.squareup.moshi.Json

data class Response(
    @field:Json(name="data") val data: ResponseData
)

data class ResponseData(
    @field:Json(name="posts") val posts: Posts
)

data class Posts( …

How to get trending repos on GitHub using Retrofit

Issue #367

https://api.github.com/search/repositories?sort=stars&order=desc&q=language:javascript,java,swift,kotlin&q=created:>2019-08-21
interface Api {
    @GET("https://api.github.com/search/repositories")
    suspend fun …

How to use Retrofit in Android

Issue #366

Code uses Retrofit 2.6.0 which has Coroutine support

app/build.gradle

implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01"

implementation "com.squareup.moshi:moshi:$Version.moshi"

implementation …

How to inject view model with Koin in Android

Issue #359

app/build.gradle

implementation "org.koin:koin-core:$Version.koin"
implementation "org.koin:koin-androidx-scope:$Version.koin"
implementation "org.koin:koin-androidx-viewmodel:$Version.koin"

MyApplication.kt

import …

How to use coroutine LiveData in Android

Issue #358

app/build.gradle

implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01"
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import kotlinx.coroutines.Dispatchers

class MainViewModel : ViewModel …

How to declare generic RecyclerView adapter in Android

Issue #357

generic/Adapter.kt

package com.onmyway133.generic

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class Adapter<T>(var items: …

How to use Navigation component with DrawerLayout in Android

Issue #349

Screenshot_1565169686

build.gradle

dependencies {
    classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha05'
}

app/build.gradle

apply plugin: 'androidx.navigation.safeargs'

dependencies {
    def navigationVersion …

How to organise test files

Issue #327

In terms of tests, we usually have files for unit test, UI test, integeration test and mock.

Out of sight, out of mind.

Unit tests are for checking specific functions and classes, it’s more convenient to browse them side by side …

How to use Gradle Kotlin DSL in Android

Issue #285

kts

settings.gradle.kts

include(":app")

build.gradle.kts

import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.kotlin
import org.gradle.kotlin.dsl.*
import …

Getting to know some pragmatic programming language features

Issue #270

As you know, in the Pragmatic Programmer, section Your Knowledge Portfolio, it is said that

Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different …

Using camelCase for abbreviations

Issue #147

Each language and platform has its own coding style guide. This goes true when it comes to abbreviations. I’ve had some debates about whether to use JSON or Json, URL or Url, HTTP or Http.

I personally prefer camelCase, so I’m …

How to use Function Literals with Receiver in Kotlin

Issue #139

From https://kotlinlang.org/docs/reference/lambdas.html

class HTML {
    fun body() { ... }
}

fun html(init: HTML.() -> Unit): HTML {
    val html = HTML()  // create the receiver object
    html.init()        // pass the receiver …

Understanding suspend function in Kotlin Coroutine in Android

Issue #123

Getting to know Coroutine

From https://kotlinlang.org/docs/reference/coroutines.html

To continue the analogy, await() can be a suspending function (hence also callable from within an async {} block) that suspends a coroutine until some …

Understanding let, apply, with, run in Kotlin

Issue #114

Picture worths thousand words. Code worths thousand pictures. I don’t understand much until I take a look at Standard.kt in Kotlin standard library.

/**
 * Calls the specified function [block] with `this` value as its receiver and …

Communication between Fragment and Activity

Issue #108

There’s always need for communication, right 😉 Suppose we have OnboardingActivity that has several OnboardingFragment. Each Fragment has a startButton telling that the onboarding flow has finished, and only the last Fragment shows …