0

Hi I have an TextView in my android studio project. I want to access it. I know it can be done through

val myText = findViewById<TextView>(R.id.textView)

but everytime I make new function I need to declare val of myText using above code line. Like This:-

fun onDigit(view: View){
val textView = findViewById<TextView>(R.id.textView)
    textView.append((view as Button).text)
}

fun onClear(view: View){
val textView = findViewById<TextView>(R.id.textView)
    textView.text = ""
}

Is there any way to universally declare it and access it without declaring it in every function?

1
  • make it lateinit var class level field Commented Jul 6, 2021 at 11:59

1 Answer 1

1

Yes, you can keep a reference to your view in a property from the activity or fragment. It will look like this:

// Declare the view as property
private lateinit var myText: TextView

// Then in onCreate save a reference to it
override fun onCreate(savedInstanceState: Bundle?) {
     ....
     myText = findViewById<TextView>(R.id.textView)
}

// After this point, you can access the view as any global variable
fun onDigit(view: View) {
    myText.append((view as Button).text)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.