'Binding Inheritance
Scenario: 2 Fragment-classes with different xml-files => 2 different Bindings, but I gave the objects within the xml the same IDs.
What I want: to use the binding code in Functions boo() & foo() of A also for B, the only difference is the "Binding-Object" (see the code).
Problem: Function boo() and foo() can only access the binding of A. So the attribute "number" in B throws the error when it calls the binding in method boo: "lateinit property binding has not been initialized".
Fragment_A:
open class Fragment_A : Fragment() {
private lateinit var binding: Fragment_A_Binding
lateinit var number: EditText
override fun onCreateView( ... ): View {
binding = Fragment_A_Binding.inflate(inflater, container, false)
binding.button_1.setOnClickListener{
boo()
}
binding.button_2.setOnClickListener{
foo()
}
}
fun boo() {
//doStuff with Bindings, e.g.
number = binding.textView_1 //calls object in xml-file
}
fun foo() {
//doStuff with Bindings
}
}
and Fragment_B which inherits from A:
class Fragment_B : Fragment_A() {
private lateinit var binding: Fragment_B_Binding
// lateinit var number: EditText //is inherited
override fun onCreateView( ... ): View {
binding = Fragment_B_Binding.inflate(inflater, container, false)
binding.button_1.setOnClickListener{
boo()
}
binding.button_2.setOnClickListener{
foo()
}
}
}
I have no idea how to solve this problem without double the code for Fragment_B for all binding-calls. This would be terrible..
Solution 1:[1]
You can create one common class which holds these two functions boo() and foo() and declare your functionalities there. Functions boo() and foo() will accept parameter of binding which you will pass from the fragment. See example below:
class CommonClass {
companion object {
fun boo(firstFragmentBinding: Fragment_A_Binding? = null,secondFragmentBinding: Fragment_B_Binding? = null ) {
val binding = when {
firstFragmentBinding != null -> {
firstFragmentBinding
}
secondFragmentBinding != null -> {
secondFragmentBinding
}
else -> {
null
}
}
binding?.let {
/// Perform your operations here
}
}
fun foo() {
}
}
}
You can have perform same operation of boo() function in foo() function.
Now, from the fragment you can simply call like,
Fragment_A_Fragment:
CommonClass.boo(firstFragmentBinding = binding)
Fragment_B_Binding:
CommonClass.boo(secondFragmentBinding = binding)
Hope this helps!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vraj Shah |
