LoginSignup
12

More than 5 years have passed since last update.

adapterについて

Posted at

Adapterとは

android studioでlistViewを使う際にはadapterを使わなければなりません。
adapterのはdeveloperでは

Adapter object acts as a bridge between an AdapterView and the underlying data for that view.

つまりAdapterViewなどのViewとデータの橋渡しをしています。

ArrayAdapter

http://qiita.com/nimani76/items/032d0d6d01f7bfd6a5e4
ここで使ったadapterはArrayAdapterというもので

val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1)

このように使っています。
thisはContext情報を渡しています。
Conrextとはアプリケーション全体の状態の情報(かな?)のことでその情報を渡しています。
android.R.layout.simple_list_item_1とはandroidSDKに標準で準備されているレイアウトファイルのIDをあらわすもの。
この二つのコンストラクタ以外にもandroid.R.layout.simple_list_item_1のうしろにlistのデータを渡すこともできます。

adapterの種類

adapterはArrayadapter以外にもCursorAdapter,SimpleAdapter,BaseAdapterがあります。

SimpleAdapter

SimpleAdapterはMLファイルで定義された複数のビューを表示するときに使用します。
コードはSimpleAdapter(this, listData, R.layout.list,arrayOf("no", "name"), intArrayOf(R.id.no, R.id.name))
thisはContext情報を渡すもの。
listDataはmapのlistでデータを表示するコンストラクト。
R.layout.listはlistviewに表示するウィジェットの定義されているID。arrayOf("no", "name")は表示するデータのmapのキー。
intArrayOf(R.id.no, R.id.name)はlistviewに表示するウィジェットが定義するresourcesのなかのウィジェットのID。

BaseAdapter

BaseAdapterはBaseAdapterを継承することで独自のadapterを作る場合に使用します
例として

origadapter.kt
import android.view.ViewGroup
import android.view.LayoutInflater
import android.widget.ArrayAdapter
import android.view.View
import com.example.nimani.listas2.R

class origadapter(context: Context, objects: List<HashMap<String, String>>) : BaseAdapter<HashMap<String, String>>(context, 0, objects) {
    private val mInflater: LayoutInflater
    private var mTitle: TextView? = null
    private var mDesc: TextView? = null

    init {
        mInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list, null)
        }

        val item = this.getItem(position)
        if (item != null) {
            mTitle = convertView!!.findViewById(R.id.title)
            mTitle!!.text = item["title"]

            mDesc = convertView!!.findViewById(R.id.desc)
            mDesc!!.text = item["desc"]
        }
        return convertView!!
    }
}

のように継承して使用します。

CursorAdapter

CursorAdapterとはCursorクラスでアクセスする場合に使います。
今回は省略

参照

MitoRoid
http://mitoroid.com/category/android/android_listview1.php

Android開発でList Viewを使おう!
http://qiita.com/Tsumugi/items/47f31bb7351979a45653

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
12