I am a beginner in Android. I am using a custom view class, let's say CustomView which looks like:
class CustomView(context: Context?,attributeSet: AttributeSet) : View(context) {
class CustomView constructor(context: Context?, attributeSet: AttributeSet){
}
var number = 1
}
I am inflating this view inside my view in main activity resource, like:
<com.example.myapp.CustomView
android:id="@+id/custom_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Now, what I want to do is, click a button on main activity and modify the value of number and also get the modified value of number in main activity.
Like, clicking a button in main activity, changing the value of number to 2 and displaying the modified value inside main activity.
Is it possible?
Using simple setter and getter functions
class CustomView constructor(context: Context?, attributeSet: AttributeSet){
var number = 1
fun getNumber(){
return number
}
fun setNumber(num: Int){
number = num
}
}
And calling them like
val customView: CustomView = findViewById(R.id.custom_view)
customView.setNumber(2)
var num = customView.getNumber()
With getter and setter, it will work just fine with private access modifier too.