I have tried to simplify my problem as much as possible, I hope it is clear what I am asking.
I would like to obtain in the fragment the value of the variable pto1 after modifying it through the onClickEvent function of class B. I understood that doing so is not possible because when I have
val classA = A ()
in the fragment,a new instance of class A is recreated and a new pto1 it is recreated and set to 0.0 .
how can i access pto1 from fragment after modifying it with class B?
class A {
var pto1 = 0.0
fun changeValue(a: Double){
pto1 = a
}
}
--------------------------------
class B {
val classA = A()
fun onClickEvent(b:Double){
classA.changeValue(b)
}
}
--------------------------------
fragment D {
val classA = A()
onCreateView( ... ){
val botton = view.findViewById<Button>(R.id.button)
button.setOnClickListner{
val f = classA.pto1
}
}
}
CodePudding user response:
There is a couple of options here
Make it static
class A {
companion object {
var pto1 = 0.0
}
}
Is this a View Model problem?
Use the navgraph viewmodel or a viewmodel from the activity.
Make it persistent: you can use the SharedPreferences
or ROOM to save it.
Make the host of both fragments have it and then fragments can acces it. If the host is the activity:
class MyActivity {
val a = A()
fun getA() = a
}
(requireActivity() as? MyActivity).?getA()
Is this a navigation result? Take a look here How to get a result from fragment using Navigation Architecture Component?