androidbroadcast / ViewBindingPropertyDelegate

Make work with Android View Binding simpler
https://proandroiddev.com/make-android-view-binding-great-with-kotlin-b71dd9c87719
Apache License 2.0
1.43k stars 102 forks source link

Add Activity viewBinding without view id #6

Closed chet-chen closed 4 years ago

kirich1409 commented 4 years ago

Hi. What is the use case for that API?

chet-chen commented 4 years ago

Like ProfileFragment in samples, ProfileActivity can be simpler.

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

    private val viewBinding: ProfileBinding by viewBinding()
}
class ProfileActivity : AppCompatActivity(R.layout.profile) {

    private val viewBinding: ProfileBinding by viewBinding(R.id.container)
}

With new API:

class ProfileActivity : AppCompatActivity(R.layout.profile) {

    private val viewBinding: ProfileBinding by viewBinding()
}
kirich1409 commented 4 years ago

I checked such kind of solution before 1.0. Root of a ViewBinding must be specified in activity, because it's not obvious what to take. WIth Fragment ut's obvious what to take. I don't want to make confusion for activity.

premacck commented 3 years ago

@kirich1409 I think we can provide the first view inside the android.R.id.content ViewGroup as the default view, in the "without reflection" approach like this:

public inline fun <A : ComponentActivity, T : ViewBinding> ComponentActivity.viewBinding(
  crossinline vbFactory: (View) -> T, crossinline viewProvider: (A) -> View = { window.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) }
): ViewBindingProperty<A, T> {
  return viewBinding { activity: A -> vbFactory(viewProvider(activity)) }
}

And use it like this: private val binding by viewBinding(ProfileBinding::bind)

This is working for Activities with the layoutRes ID passed as parameter.

This will come in handy in those cases where there aren't any view IDs associated with the root layout of the Activity.

I am migrating a big project from kotlin synthetic properties to view binding, and I don't have a root layout ID in almost all my Activities, so instead of adding them in all places, this default value can save me a lot of time

kirich1409 commented 3 years ago

@premacck , good idea. I'll try to implement it in 1.4.0

premacck commented 3 years ago

@kirich1409 Any ETA on the 1.4.0 release?

kirich1409 commented 3 years ago

I will work on it during the next week

premacck commented 3 years ago

Okay, in the meanwhile, may I offer a PR for the above change? :)

kirich1409 commented 3 years ago

Yes. It will be good to check another point of view

kirich1409 commented 3 years ago

Yes. It will be good to check another point of view

premacck commented 3 years ago

@kirich1409 Opened #32