Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global object declaration in kotlin

How to declare objects globally in kotlin like in java TextView tv;.

Or any method to call the same variable in different methods/functions.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val textView: TextView = findViewById(R.id.texfirst) as TextView 

    textView.setOnClickListener {
        Toast.makeText(applicationContext,"Welcome to Kotlin ! $abc "+textView.text, Toast.LENGTH_LONG).show()
    }

    myFunction(textView)
}

fun myFunction(mtextv : TextView) {
    Toast.makeText(applicationContext,"This is  new  $abc "+mtextv.text, Toast.LENGTH_LONG).show()
}

See the above code I've separate function with parameter of TextView. I want the TextView object at second function. My question is: Is it possible to call function without parameter and am I able to get TextView object at myFunction().

Learning kotlin in android studio. Hope question is clear .

like image 797
SARATH V Avatar asked Aug 18 '17 07:08

SARATH V


People also ask

How do I declare a global variable in Kotlin?

This example demonstrates how to declare global variables on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is object declaration in Kotlin?

Kotlin object Expressions. The object keyword can also be used to create objects of an anonymous class known as anonymous objects. They are used if you need to create an object of a slight modification of some class or interface without declaring a subclass for it. For example , window.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


1 Answers

The one you are mentioning is class property.

For your case, you need to declare a TextView in an Activity class and do the assignment by calling findViewById() in onCreate().

class YourActivity {

    lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView = findViewById(R.id.texfirst) as TextView
        //implementation
    }

    fun myFunction() {
        Toast.makeText(applicationContext, "This is  new $abc " + textView.text, Toast.LENGTH_LONG).show()
    }
}
like image 71
BakaWaii Avatar answered Sep 29 '22 01:09

BakaWaii