I'm newbie.
I want to change text of TextView
While click on it.
My code:
val text: TextView = findViewById(R.id.android_text) as TextView
text.setOnClickListener {
text.setText(getString(R.string.name))
}
Output: I got the output but showing use property access syntax.
Can anyone tell me how to do it?
Thanks in advance.
In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
To get the values from the Textview
we have to use this method
val str: String = textView.text.toString()
println("the value is $str")
just add below line and access direct xml object
import kotlinx.android.synthetic.main.activity_main.*
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txt_HelloWorld.text = "abc"
}
replace activity_main according to your XML name
Find the text view from the layout.
val textView : TextView = findViewById(R.id.android_text) as TextView
Setting onClickListener on the textview.
textview.setOnClickListener(object: View.OnClickListener {
override fun onClick(view: View): Unit {
// Code here.
textView.text = getString(R.string.name)
}
})
Argument parentheses can be omitted from View.setOnClickListener if we pass a single function literal argument. So, the simplified code will be:
textview.setOnClickListener {
// Code here.
textView.text = getString(R.string.name)
}
Use:
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
Or:
you can annotate every call site with @Suppress("UsePropertyAccessSyntax")
, but that’s ugly.
<TextView
android:id="@+id/usage"
android:layout_marginTop="220dip"
android:layout_marginLeft="45dip"
android:layout_marginRight="15dip"
android:typeface="serif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Google "
android:textColor="#030900"/>
usage.text="hello world"
import kotlinx.android.synthetic.main.MainActivity.*
class Mainactivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.MainActivity)
txt.setText("hello Kotlin")
}
}
val text: TextView = findViewById<TextView>(R.id.text_id) as TextView
findViewById(R.id.android_text) does not need typecasting.
The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.
val text: TextView = findViewById(R.id.android_text) as TextView
Where 'android_text' is the ID of your textView