【Android App with Kotlin #3】ListViewを使う
まずはListViewに適当なデータを表示させるシンプルなものを用意しました。
作るもの
ListviewActivity.kt内で宣言したString型のコレクションを表示させるListViewです。
環境
このコードは以下の環境で書いています。
- macOS 10.14.2(Mojave)
- Android Studio 3.2.1
- Android SDK 28
- gradle 4.6
事前準備
特にありません。 表示させるアイテムのネタを考えておきましょう。
レイアウトファイル
デザインタブから「ListView」を挿入します。
Paletteの
Legacy
に入っているので注意しましょう。
テキストタブでレイアウトやコードの微修正します。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lvHeroes"
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
Activityファイル
class ListviewActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.listview_activity)
val heroes:Array<String> = arrayOf("Iron Man", "Captain America", "Thor") //[1]
val adapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, heroes) //[2]
val lvHeroes: ListView = findViewById(R.id.lvHeroes) //[3]
lvHeroes.adapter = adapter //[4]
}
}
コードの説明に入ります。
[1]
String型が格納されるコレクション(配列)を宣言すると同時に値を代入しています。
[2]
ListViewというレイアウトと、[1]
で宣言したコレクションを紐付けるアダプターです。
this
コンテキストです。まだ自分もよくわかっていないので調べて加筆します。android.R.layout.simple_list_item_1
はじめから用意されているListViewの項目1つ分のレイアウトです。 独自のレイアウトを適用させる場合は、この引数を変える事になります。heroes
[1]
で宣言したコレクションの名前で、アダプターにセットしています。
[3]
レイアウトファイルで用意したListView
をActivityファイルで使えるように宣言しています。
Kotlin Andorid extentionsが有効であれば、この項目は書かなくてもレイアウトファイルで
宣言したandroid:id
でそのまま扱えます。
[4]
[3]
で宣言したListView
と、[2]
で宣言したadapterを紐づけています。
リンク
次の記事
次回はListViewで用意したアイテムにタッチすると 処理が実行されるようにします。 【Android App for Kotlin #4】ListViewを使う(2)
前回の記事
【Android App with Kotlin #2】画像を取り扱う(ImageView/ImageButton)
/以上