Declaring variables outside of a function in kotlin?

Viewed 551

code at the bottom works flawlessly

class MainActivity : AppCompatActivity() {

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

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

But I wanna write this line val tvInput = findViewById<TextView>(R.id.tvInput) outside of the functions onDigit and onClear (because it appears two times).

If I put out the line, code looks like;

class MainActivity : AppCompatActivity() {

val tvInput = findViewById<TextView>(R.id.tvInput)

fun onDigit (view: View){
    tvInput.append((view as Button).text)
}

fun onClear (view: View){
    tvInput.text = ""
}}

But the code didn't work. The app crashes after I'm trying to start it and throws an error app keeps stopping

Maybe it's an easy problem but couldn't find the solution therefore thanks in advance :)

1 Answers

You need to create a global variable first and assign it into onViewCreated() [for Fragment] or onCreateView() or onCreate() functions .

class MainActivity : AppCompatActivity() {

private var tvInput : TextView ? = null
//override this function (Ctrl + O)

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
      val view = //Inflate your view here 
      tvInput = view. findViewById<TextView>(R.id.tvInput) 
      return view 

}
fun onDigit (view: View){
    tvInput.append((view as Button).text)
}

fun onClear (view: View){
    tvInput.text = ""
}}

and then you can use it anywhere

Related