Skip to content

dongheeleeme/ButterKt

 
 

Repository files navigation

ButterKt

ButterKt is an improved version of KotterKnife. It solves the following problems of KotterKnife:

  • Lazy binding is dangerous if a layout ID is used in multiple files.
  • Unbind call for Fragment

For the detailed explanation, see the following article.

Installation

Currently, ButterKt does not support installation as a dependency. As the code is short, I recommend you to copy ButterKt.kt into your source code.

Actual Usage

Activity, View, Dialog

class MainActivity : AppCompatActivity() {
  private val title by bindView(R.id.item_title)

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    ButterKt.bind(this)
  }
}

Call ButterKt.bind(this) in Activity#onCreate, View#onFinishInflate, Dialog#onCreate

DialogFragment, Fragment

class TestFragment : Fragment() {
  private val title by bindView(R.id.item_title)

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?) {
    val view = inflater.inflate(R.layout.fragment_test, container, false)
    ButterKt.bind(this, view)
    return view
  }

  override fun onDestroyView() {
    super.onDestroyView()
    ButterKt.unbind(this)
  }
}

Call ButterKt.bind(this, view) in Fragment#onCreateView, and ButterKt.unbind(this)inFramgent#onDestroyView`

RecyclerView.ViewHolder

class TestViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
  private val title by bindView(R.id.item_title)

  init {
    ButterKt.bind(this)
  }
}

Call ButterKt.bind(this) in init block

ButterViewHolder (custom viewHolder)

class TestViewHolder(val view: View) : ButterViewHolder {
  private val title by bindView(R.id.item_title)

  fun someFunction1() {
    ButterKt.bind(this, view)
  }

  fun someFunction2() {
    ButterKt.unbind(this)
  }
}

Call ButterKt.bind(this, view) and ButterKt.unbind(this) if you think it's appropriate.

License

Copyright 2018 Jin-Hyung Kim
Copyright 2014 Jake Wharton

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

About

Android view binding library.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Kotlin 100.0%