F
F
foonfyrick2020-11-22 08:26:49
Android
foonfyrick, 2020-11-22 08:26:49

Why can't I use view binding in the child of the base fragment?

I made a basic snippet:

open class BaseFragment(val activity:Int) : Fragment() {
    lateinit var mView: View
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mView=LayoutInflater.from(requireContext()).inflate(activity,container,false)
        return mView
    }
}

The rest inherited from it, but the screen of the heirs is displayed only if I use synthetic imports via id, but if I create a binding and start creating a recycle view from it and interact with the buttons, then there is no error, and the screen is empty.
private lateinit var mBinding : FragmentAddBinding

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
foonfyrick, 2021-03-11
@foonfyrick

//https://chetangupta.net/viewbinding/
abstract class ViewBindingFragment<VB : ViewBinding> : Fragment() {

    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = bindingInflater.invoke(inflater, container, false)
        return requireNotNull(_binding).root
    }

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

    abstract fun setup()

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

class ProfileFragment :ViewBindingFragment<ProfileLayoutBinding>() {
  override val bindingInflater: (LayoutInflater) -> ViewBinding 
          = ProfileLayoutBinding::inflate
          
  override fun setup(){
  	//.. do stuff with binding variable
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question