省エネ

Flutter、vue3修行中。

【Android】findViewByIdはもういらない、そうKotlinなら

kotlinlang.org

Kotlin Android Extensionsというプラグインがありまして、 これを使うとこんな書き方ができるようです。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.qkuronekop.sample02.MainActivity">

    <com.google.android.flexbox.FlexboxLayout
        android:id="@+id/flexLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp" />

</LinearLayout>

MainActivity.kt

package com.example.qkuronekop.sample02

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        (0..10).forEach {
            val textView = TextView(applicationContext).apply {
                text = "aaaaaa"
            }
            flexLayout.addView(textView)
        }

    }
}

こんな感じ。 ポイントはここ。

flexLayout.addView(textView)

xmlでつけてるidをそのまま使えます。 findViewByIdもキャストも不要でコードもスッキリです。

import kotlinx.android.synthetic.main.activity_main.*

ここを見ていただくとお分りのように、activity_mainをimportする必要がありますので、ご注意ください。

詳しい使い方は一番上にリンクした公式ページにて!