LoginSignup
10
11

More than 5 years have passed since last update.

Kotlinでレイアウトを動的に変更する

Posted at

LinearLayoutに動的にViewを追加する

チャットみたいな画面が簡単に作ってみたいと思って、色々調べて、LinearlayoutにViewを追加する方法を理解したので、ノート程度の書いて行きます。

android.xml
<LinearLayout
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/send"
    android:orientation="vertical"/>

Linearlayoutをレイアウトファイルに設定しておく。

Kotlinのソースコードの方で、

MainActivity.kt
val layout = findViewById<LinearLayout>(R.id.linear)
val button = findViewById<Button>(R.id.send)

button.setOnClickListener{
    val textView: TextView = TextView(this)
    textView.text = "セットしたいテキスト"
    layout.addView(textView)
}

こちらの方法で動的に追加することが可能。
val layout = findViewById<LinearLayout>(R.id.linear)

で、LinearLayoutのlayoutを生成。そこに、引数にView型の引数を取るaddView()メソッドを使用して、動的にViewを追加していくという方法を用いた。

以上が、Layoutに動的にViewを追加していく方法でした。
このほかにもKotlinのソースコードのみで、Linearlayoutを生成する方法もあると思いますが、ここでは割愛します。

何かコメントなどあればお願いいたします。

10
11
0

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
10
11