20190310のKotlinに関する記事は3件です。

Kotlin vs. Java: Which Programming Language to Choose for Your Android App

The question is which is better Kotlin or Java. With the appearance of Kotlin this struggle started in 2011, when at the same time, Java was completely beating any new competitors off. With the help of Google and JetBrains, Kotlin was developed to eliminate any of Java’s faults. Beginning with the Google I/O 2017 Developer Conference, Kotlin started to move into a high level.

Is it possible for Kotlin to replace Java completely? Is it difficult to find good Kotlin developers? Here you will find out about this and about the benefits and drawbacks of each language.

Kotlin vs. Java: Intro to Official Android Programming Languages

Android and Java have always been connected. Android SDK is even written in Java. The situation has started to change after the invention of Kotlin. Below you will read about the differences between Kotlin vs. Java in order to understand if adopting Kotlin is worthwhile.

Java Android Development

Java is an object-oriented, class-based programming language. It was designed by a “Green Team” led by James Gosling at Sun Microsystems (now owned by Oracle Corporation) and was originally planned to serve the digital cable television industry. However, the language appeared to be too sophisticated for this purpose and found its place instead in the world of Internet programming.

Java was released in May 1995 and today there is hardly a developer who hasn't heard of it. No wonder, as it is the second most popular language on GitHub with around 70K repositories.

Apart from using Java for Android applications, developers are also able to create desktop apps and app back ends. Unsurprisingly, as it has a tremendous community and almost 25 years of usage, Java has proven to be trusted and secure.

java for android

Java vs. Kotlin: Advantages of Java

If we look at Java and Kotlin, we will see that both languages have positive characteristics worth considering when choosing between them. The advantages of Java are:

  • Easy to learn

It is the biggest advantage of Java. This means that it is easy to write, compile, and debug using Java. It has a digestible and understandable syntax and can be a good starting point while learning programming.

  • Strong community

It has almost one million repositories on GitHub. That is why, there are thousands of different libraries and frameworks which can be utilized and, as a result, speed up the development process.

  • Platform-independent

Java compiler converts the source code to bytecode, which serves as a so-called “intermediate” language. Bytecode can be executed on any platform using Java Virtual Machine. You can even write Java code on Android using a special app called Java N-IDE.

Java vs. Kotlin: Downsides of Java

Just like any other programming language, Java has its disadvantages like:

  • Verbosity

Java needs far more code to be written than Kotlin, and that is why there is a higher risk of errors.

On the other hand, Kotlin is clearer and more concise.

  • Performance

Unfortunately, Java is slow and consumes more memory space in comparison with Kotlin. Due to the need to load all the classes before work can begin, the startup time is also slower.

  • Nullability Problems

NullPoinerExceptions is a real issue for Java developers using non-nullable variables. It can be frustrating because null represents absence of value. Hence, developers need to write additional lines of code to solve this issue.

It may seem that making Android apps with Java is a dead-end job if we take into account all of this. If you want to know more about it, below you will find it out.

Recommendation: Why Use Java in 2019?

After everything mentioned above Kotlin looks like the perfect language to develop with. Why is Java still used today? Read on to find out:

There are Java gurus in a team who don't want to switch to Kotlin.
A team tried Kotlin and was unsatisfied with it.
If a successful project was developed in Java (although, it is not a problem to develop new features in Kotlin, in this case). Don't forget that Java code needs to be supported by Java if you don’t want the transition of the whole project to Kotlin.

Kotlin: New Android Language

kotlin android

Kotlin is a brand new Android programming language that was first introduced by JetBrains in 2011. It got its name from the Kotlin Island in Russia and in 2017 became the officially supported language for Android development. Kotlin can also be used for developing server-side and web client-side apps.

Since the 2017 Google I/O conference, the use of Kotlin language has started to rise exponentially. This should come as no surprise, as it was made to be completely JVM (Java Virtual Machine) compatible and compiles down to Java bytecode. This means that both Java and Kotlin code can co-exist within one project.

In 2018, a lot of huge companies switched to Kotlin as it is 100% interoperable with Java. Among such companies are Google, Uber, Trello, Pinterest, Kickstarter, and many more.

Kotlin vs. Java: Advantages of Kotlin

In spite of the fact that Kotlin is a new language, it has already shown a lot of benefits in comparison with Java. Below you will read the advantages of Kotlin:

  • Conciseness

This language is proven to be more concise than Java. It has been estimated that about 40% in the number of lines of code are cut. The quality increases because there is less space for bugs and errors.

  • Interoperability

Kotlin is completely interoperable with Java. JetBrains’ Java to Kotlin converter, integrated into IntelliJ, provides a smooth transition to Java code. Besides, Kotlin supports almost all existing Java libraries and compiles with Java compatible bytecode.

  • Functional programming support

Kotlin supports both object-oriented and functional programming. Kotlin has proper function types built in and it can help solve many problems developers face more easily.

  • Fail-fast system

Kotlin language has a built-in fail-fast system which helps to reduce bugs and avoid errors in the code. For this purpose, there are three standard library functions: check, require, and assert.

  • Supportive community

Despite the fact that it is a young language, it has quite a supportive community. Every developer can join a Kotlin Slack channel where he can get support and help from other Kotlin devs.

Learn more here. In this article you will find out which language is better Kotlin or Java.

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Android KotlinとRxBinding2

はじめに

Jake Whartonが作成したRxBinding2というライブラリをご存知でしょうか。
Viewでのイベントに対して様々な条件などを付与しsubscribeすることでViewでのアクションを制御することができます。
RxBinding2をkotlinで使う場合、kotlin用に拡張されているライブラリを利用する必要があります。

RxBinding2をkotlinで使う際の情報が少なかったので苦労しました...
基本的な利用方法を記載しているので、参考になればと思います。

  • Kotlin 1.3.21
  • Rxbinding-kotlin 2.2.0

RxBinding2の導入

kotlin拡張用のライブラリを導入する必要があるので、-kotlinを忘れないようにします。

app/build.gradle
// ...

dependencies {

    // ...
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.5'
    def rx_binding2_version = '2.2.0'
    implementation "com.jakewharton.rxbinding2:rxbinding-kotlin:$rx_binding2_version"
    implementation "com.jakewharton.rxbinding2:rxbinding-recyclerview-v7-kotlin:$rx_binding2_version"
    implementation "com.jakewharton.rxbinding2:rxbinding-appcompat-v7-kotlin:$rx_binding2_version"
    implementation "com.jakewharton.rxbinding2:rxbinding-support-v4-kotlin:$rx_binding2_version"
    implementation "com.jakewharton.rxbinding2:rxbinding-design-kotlin:$rx_binding2_version"
    implementation "com.jakewharton.rxbinding2:rxbinding-leanback-v17-kotlin:$rx_binding2_version"
}

利用方法

それぞれのライブラリの利用方法です。
一例を踏まえながら書き方を記載します。

rxbinding-kotlin

ViewにあるButtonに対してclickした際の挙動はこのように書くことができます。

val binding = DataBindingUtil.setContentView<ActivityHogeBinding>(this, R.layout.activity_hoge)
binding.demoButton
        .clicks()
        .filter { clickCount < 1 }
        .subscribe {
            clickCount++
            Log.d("debug", "click!!")
        }

rxbinding-recyclerview-v7-kotlin

ViewにあるRecyclerViewに対するアクションを制御できます。
RecyclerViewでスクロールが一番下までいったらロードする実装がこちらです。

val binding = DataBindingUtil.setContentView<ActivityHogeBinding>(this, R.layout.activity_hoge)
val gridLayoutManager = GridLayoutManager(this, 2)
// 実装例1
binding.hogeRecyclerView
        .scrollEvents()
        .filter { gridLayoutManager.itemCount - 1 <= gridLayoutManager.findLastVisibleItemPosition() }
        .subscribe { loadMore(item) }
// 実装例2
RxRecyclerView
        .scrollEvents(binding.companyRecyclerView)
        .filter { gridLayoutManager.itemCount - 1 <= gridLayoutManager.findLastVisibleItemPosition() }
        .subscribe { loadMore(item) }
fun loadMore(item: Item) {
    if (this.itemList.last().id != item.id) {
        Log.d("debug", "loadMore")
    }
}

rxbinding-appcompat-v7-kotlin

AppCompat-v7 Libraryで導入できるViewに対するアクションを制御できます。
ToolBarのitemのclickだとこのようになります。

// 実装例1
toolbar.itemClicks().subscribe{ Log.d("debug", "itemClicks") }
// 実装例2
RxToolbar.itemClicks(toolbar).subscribe{ Log.d("debug", "itemClicks") }

rxbinding-support-v4-kotlin

Support-v4 Libraryで導入できるViewに対するアクションを制御できます。
SwipeRefreshLayoutのrefreshだとこのようになります。

// 実装例1
binding.hogeFragmentSwipeRefreshLayout
        .refreshes()
        .subscribe { Log.d("debug", "refreshes") }
// 実装例2
RxSwipeRefreshLayout
        .refreshes(binding.hogeFragmentSwipeRefreshLayout)
        .subscribe { Log.d("debug", "refreshes") }

rxbinding-design-kotlin

Design Support Libraryで導入できるViewに対するアクションを制御できます。
NavigationViewのitem選択時の挙動だとこのようになります。

// 実装例1
binding.demoNavigationView
        .itemSelections()
        .subscribe { Log.d("debug", "itemSelections") }
// 実装例2
RxNavigationView
        .itemSelections(binding.demoNavigationView)
        .subscribe { Log.d("debug", "itemSelections") }

rxbinding-leanback-v17-kotlin

Leanback-v17 LibraryはAndroidTV向けのライブラリです。
今回は利用していないので、rxbinding-leanback-v17-kotlinについてはパスします。

最後に

RxBinding2の基本的な使い方を書きました。
kotlinの拡張関数との組み合わせや、他のRx系のライブラリと組み合わせることで、
よりシンプルに書くこともできそうだと感じました。
リアクティブプログラミングはまだ全然慣れていないので、良い実装例があれば勉強したいので教えていただけると嬉しいです。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

TextInputLayout - password visibility toggleのデザイン変更

:lock: はじめに

Androidのマテリアルデザインに沿った入力フィールドを作成するのに、Android Design Support Libraryの TextInputLayout を使うことが多いかと思います。これにはパスワードの表示/非表示を切り替える機能( password visibility toggle )が備わっているのですが、デザインを変更する際に少しハマったのでメモします。

:lock: 実装

変更箇所

パスワードの表示/非表示を切り替えるボタン( password visibility toggle button )のアイコンと色をそれぞれ切り替えます。

失敗例

ic_password_toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <bitmap android:src="@drawable/ic_lock" android:tint="#9e9e9e" />
    </item>
    <item android:state_checked="true">
        <bitmap android:src="@drawable/ic_lock_open" android:tint="@color/colorAccent" />
    </item>
</selector>
activity_main.xml
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:hintAnimationEnabled="true"
    app:hintEnabled="true"
    app:passwordToggleDrawable="@drawable/ic_password_toggle"
    app:passwordToggleEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_password"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

パッと見これで問題なさそうですが、 passwordToggleTint を指定していないので、デフォルトで塗りつぶされてしまい、色が切り替わりません。

成功例

ic_password_toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_lock" android:state_checked="false" />
    <item android:drawable="@drawable/ic_lock_open" android:state_checked="true" />
</selector>
tint_password_toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#9e9e9e" android:state_checked="false" />
    <item android:color="@color/colorAccent" android:state_checked="true" />
</selector>
activity_main.xml
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:hintAnimationEnabled="true"
    app:hintEnabled="true"
    app:passwordToggleDrawable="@drawable/ic_password_toggle"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="@color/tint_password_toggle">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_password"
        android:inputType="textPassword" />

</android.support.design.widget.TextInputLayout>

passwordToggleDrawablepasswordToggleTint に分けてそれぞれ設定するのがミソです。

screen.gif

:lock: まとめ

公式のリファレンスはちゃんとに読みましょう(戒め)。一応 GitHub にサンプルをアップしておきます。

:lock: 参考文献

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む