diadia

興味があることをやってみる。自分のメモを残しておきます。

kotlin android layoutinflateについて調べる

レイアウトファイルを動的に(pragramaticaly)結合する

参考:
(java)https://zawapro.com/?p=138
(java)https://akira-watson.com/android/inflate.html
(kotlin) https://ithelp.ithome.com.tw/articles/10203735

方法

  • Adapterを使う
  • LayoutInflaterを使う

リストビューにレイアウトファイルを追加する方法としては、adapterを用いる。例えばSimpleAdapterを用いれば以下のようにすることができる。

val adapter = SimpleAdapter(applicationContext, item_list, R.layout.item_row, FROM, TO)
// R.layout.item_rowは自作した別のレイアウトファイル

リストビューにアダプタを使うことでAdapterクラスインスタンス生成時に作成したレイアウトファイルをリストビューにくっつけることで、結果的にレイアウトファイル同士を結合させている。

 

その他の結合方法としてレイアウトインフレイトがある。LayoutInflaterについては明確な説明がある。

用來將 res/layout/ 下的 xml 佈局文件加載成 View

訳は”res / layout /の下のxmlレイアウトファイルをViewにロードするために使用されます。”である。

LayoutInflaterを使えば動的にレイアウトxmlからViewを生成できる。LayoutInflaterはActivityのgetLayoutInflater()メソッドを使うとlayoutInflaterを取得できる。その他LayoutInflaterを取得する方法はいくつかある。

layoutinflaterを取得する方法

    • LayoutInflater.from(context)
val inflater = LayoutInflater.from(context)
    • getLayoutInflater()
val inflater = getLayoutInflater()
    • Context.getSystemService(serviceClass: Class<T>
val inflater = getSystemService(LayoutInflater::class.java) as LayoutInflater
    • Context.getSystemService(name: String )
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

Viewにレイアウトファイルを読み込む方法

inflate (resource: Int, root: ViewGroup, attachToRoot: Boolean)

val view = inflater.inflate(R.layout.image, viewGroup, fasle)