Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ankoで触れるKotlin

 Ankoで触れるKotlin

Avatar for Yoshida Seisuke

Yoshida Seisuke

July 05, 2017

Other Decks in Programming

Transcript

  1. • ͸΍͍ → XML͕஗͍ • Anko Layouts DSL Ͱ Type

    Safety • CustomView ͳͥAnko͸͍͍ͷʁ
  2. relativeLayout {
 lparams(width = matchParent, height = dimen(R.dimen.action_bar_size))
 leftButton =

    ankoView(::ToolbarButton, 0) {
 id = generateViewId()
 toolbarType = [email protected]
 }.lparams(height = matchParent) {
 centerVertically()
 } 
 rightButton = customView<ToolbarButton> {
 id = generateViewId()
 }.lparams(height = matchParent) {
 alignParentRight()
 centerVertically()
 } 
 centerLayout = linearLayout {
 gravity = Gravity.CENTER
 }.lparams(width = matchParent) {
 rightOf(leftButton)
 leftOf(rightButton)
 centerInParent()
 }
 }
 Anko Layouts DSL
  3. • ࡞Δͷ؆୯ɺ ViewΛܧঝͯ͠ constructorʹContextΛ͚࣋ͭͩ • ࢖͏ͷ؆୯ val button = customView<ToolbarButton>

    { … } val button = ankoView(::ToolbarButton, 0) { … } • Define Custom Attributes ͸͍΍Ͱ͠ΐʁ https:// developer.android.com/training/custom-views/create-view.html Custom View
  4. Custom View inline fun <T : View> ViewManager.ankoView(factory: (ctx: Context)

    -> T, theme: Int, init: T.() -> Unit): T {
 val ctx = AnkoInternals.wrapContextIfNeeded(AnkoInternals.getContext(this), theme)
 val view = factory(ctx)
 view.init()
 AnkoInternals.addView(this, view)
 return view
 } 
 inline fun <reified T : View> ViewManager.customView(theme: Int = 0, init: T.() -> Unit): T {
 return ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() }
 } 

  5. Custom View class UserListAdapter : BaseAdapter<User>() {
 
 override fun

    onBindBasicItemView(holder: RecyclerView.ViewHolder, position: Int) {
 if (holder is UserViewHolder) {
 holder.bind(getBaseItem(position))
 }
 }
 
 override fun onCreateBasicItemViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
 return UserViewHolder(holderView(parent))
 }
 
 fun holderView(parent: ViewGroup): UserView = with(AnkoContext.create(parent.context, parent)) {
 customView { textView = textView { …
 } 
 }
 }
 
 class UserView(ctx: Context) : _LinearLayout(ctx) {
 lateinit var textView: TextView
 }
 
 inner class UserViewHolder(val view: UserView) : RecyclerView.ViewHolder(view) {
 fun bind(user: User) {
 view.textView.text = user.name
 }
 } }

  6. • Anko͸Id࡞Δͷ͕େมʁ @+id/໰୊ • generateViewId͕͋ΔΑ fun View.generateViewId(): Int {
 return

    if (Build.VERSION.SDK_INT >= 17) {
 View.generateViewId()
 } else {
 this.hashCode()
 }
 } RelativeLayout
  7. fun <T : View > T.onGlobalLayoutAction(once: Boolean = true, action:

    T.() -> Unit) {
 viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
 override fun onGlobalLayout() {
 action()
 if (once) {
 this@onGlobalLayoutAction .viewTreeObserver.removeOnGlobalLayoutListener(this)
 }
 }
 })
 } OnGlobalLayout