LoginSignup
66
56

More than 3 years have passed since last update.

Kotlin Android Extensionsを試してみた

Last updated at Posted at 2015-10-16

Kotlin始めました

  • 久しぶりにAndroidを書くのですが、せっかくなのでKotlinを始めてみるかと思い、Android Studioにplugin入れようとしたところKotlin Android ExtensionsというPluginも合わせて検索結果に表示されて、なんぞ?と思い使ってみました。
  • 検索するとKotlinのチュートリアルにも出てきました。どうやらfindViewByIdをいい感じにしてくれるみたい。
  • 公式はこちら。https://kotlinlang.org/docs/tutorials/android-plugin.html

使い方

1) Pluginを追加してbuild.gradleにdependencyを追加

build.gradle
    apply plugin: 'kotlin-android-extensions'

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }

2) importする

MainActivity.kt
import kotlinx.android.synthetic.main.activity_main.*
  • syntheticの次はLayoutのxml名を指定する。この場合はactivity_main.xmlを取り込んでいる。
  • これで準備完了。importしたxmlのコンポーネントを簡単に参照できるようになります。

3) コードを書いてみる

  • helloでIDを振ってあるTextViewにテキストをセットするコード。
  • Android Javaで書いたコード
MainActivity.java
TextView textView = findViewById(R.id.hello);
textView.setText("Hello Kotlin !!");
  • Kotlin Android Extensionsを使ったコード
MainActivity.kt
hello.text = "Hello Kotlin !!"
  • という感じで幸せになれるのでKotlinを新しく始める方はセットで入れておくといいと思います。

2015/10/19追記

  • 早速書き始めたらこけた。。。下のようにViewに追加するとクラスが見つからないと言われて死にます。
    <AppCompatButton
        android:id="@+id/open_hogehoge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="なんか開く" />
  • AppCompatButtonをフルパスで指定したらビルド通りました。Support library系のコンポーネント使うときは注意しないといけないですねー
    <android.support.v7.widget.AppCompatButton
        android:id="@+id/open_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open sample of listView" />
66
56
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
66
56