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.42k stars 102 forks source link

My viewBinding not work #91

Closed DanteAndroid closed 2 years ago

DanteAndroid commented 2 years ago

Hi, I've read your article about viewbinding and found it very useful. So I'm trying to write a version of mine. But it doesn't work. This is view binding util code:

class ViewBinding<T : ViewBinding>(
    private val fragment: Fragment,
    private val vbClass: Class<T>
) : ReadOnlyProperty<Fragment, T> {

    private val message = "should never try get ViewBinding when it might not be available"
    private var _value: T? = null

    override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
        _value?.let { return it }
        _value = createViewBinding(vbClass, fragment.layoutInflater)
        return _value ?: throw IllegalStateException(message)
    }

    @Suppress("UNCHECKED_CAST")
    private fun createViewBinding(clzz: Class<T>, inflater: LayoutInflater): T =
        Class.forName(clzz.canonicalName!!).getMethod("inflate", LayoutInflater::class.java)
            .invoke(null, inflater) as T

}

inline fun <reified T : ViewBinding> Fragment.mViewBinding() = ViewBinding(this, T::class.java)

And in fragment:


class LoginFragment : Fragment(R.layout.login_fragment) {

    private val binding: LoginFragmentBinding by mViewBinding()

//    private val binding : LoginFragmentBinding by viewBinding()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        with(binding) {
            message.text = "test"
            message.setOnClickListener {
                findNavController().navigate(R.id.action_loginFragment_to_mainActivity)
                activity?.supportFinishAfterTransition()
            }
        }
    }
}

Could you please help me figure it out?

DanteAndroid commented 2 years ago

not work means the message doesn't change to "test" and onClickListenner not triggered. But with your library all works fine.

kirich1409 commented 2 years ago

It's because your ViewBinding delegate inflate new View and doesn't set assign to Fragment. Update of view is successful, but Fragment shows another View as content

kirich1409 commented 2 years ago

Instead of call "inflate", true to use "bind" and get existed view from Fragment