LoginSignup
5
5

More than 5 years have passed since last update.

Ankoで Adapterの getViewを実装

Posted at

Ankoで viewをつくると attachされてしまう?

Ankoで Adapterの getViewを実装するのに 手間取ってました
getView は、親 Viewに attachしてはいけませんが、Ankoで attachせずに Viewを生成する方法がわからなかったからです。ちなみに、attachしてしまうと以下の様な例外が発生します:

 java.lang.UnsupportedOperationException: addView(View)
            is not supported in AdapterView
            at android.widget.AdapterView.addView()

UiHelperというものを使うと attachされてない Viewを作れる!

答えは anko-template-project にありました。

dsl という extensionをはやして、そこで UiHelperに適用するのが idiomのようです:
ListItemAdapter.kt


  public inline fun <T: Any> dsl(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: UiHelper.() -> T): T {
        var view: T? = null
        getContext().UI { view = f() }
        return view!!
    }

これで 自分の projectも Ankoをとりこむことができました。めでたしめでたし。

5
5
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
5
5