Skip to content

Latest commit

 

History

History
137 lines (101 loc) · 3.23 KB

README.md

File metadata and controls

137 lines (101 loc) · 3.23 KB

viewbinding-ktx

Version License

A set of Kotlin extensions for dealing with ViewBinding.


Installation

Add the dependency:

repositories {
    mavenCentral()
    google()
}

dependencies {
    implementation("com.redmadrobot.extensions:viewbinding-ktx:4.2.1-0")
}

Enable ViewBinding in build script:

android {
    // For Android Gradle Plugin 4.0+
    buildFeatures.viewBinding = true

    // For Android Gradle Plugin prior to 3.6
    viewBinding.isEnabled = true
}

Usage

Delegate

For Fragments' layouts use ViewBinding delegate. Resulting binding bounded to Fragment View's lifecycle. It will be cleared after onDestroyView.

class ProfileFragment : Fragment(R.layout.fragment_profile) {

    private val binding: FragmentProfileBinging by viewBinding()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        with(binding) {
            // use binding fields
        }
    }
}

Extensions

Inflate ViewBinding using LayoutInflater:

class PickDateFragment : DialogFragment() {

    private lateinit val binding: DialogPickDateBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = inflater.inflateViewBinding(container, attachToRoot = false)
        return binding.root
    }
}

Inflate ViewBinding using Context:

fun createDetailsView(card: Card): MaterialTextView {
    return requireContext().inflateViewBinding<ViewCardDetailsBinding>().apply {
        name.text = card.name
        //...
    }
}

Inflate ViewBinding and attach it to ViewGroup:

class ErrorView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val binding: ViewErrorBinding = inflateViewBinding()
}

Obtain ViewBinding from inflated view:

class TransactionsItem : Item {

    override val layoutId = R.layout.item_transaction

    private lateinit var binding: ItemTransactionBinding

    override fun bind(viewHolder: RecyclerView.ViewHolder) {
        binding = viewHolder.itemView.getBinding()
        with(binding) {
            // ...
        }
    }
}

Contributing

Merge requests are welcome. For major changes, please open an issue first to discuss what you would like to change.