Memin
Memin

Reputation: 23

Declaring variables outside of a function in kotlin?

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 :)

Upvotes: 2

Views: 1754

Answers (1)

Karunesh Palekar
Karunesh Palekar

Reputation: 2345

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

Upvotes: 3

Related Questions