Hi I am making a app with Kotlin and I found that I can both use
textView.setText(str)
and
textView.text = $str
I wanna know what I should use and the differences between them. Thank you.
The basic difference is that setText() replaces all the text from the existing one and append() adds your new value to existing one.
EditText is used for user input. TextView is used to display text and is not editable by the user. TextView can be updated programatically at any time.
Set The Text of The TextView You can set the text to be displayed in the TextView either when declaring it in your layout file, or by using its setText() method. The text is set via the android:text attribute.
Sets the TextView to display the specified slice of the specified char array. Sets the text to be displayed using a string resource identifier. the resource identifier of the string resource to be displayed Java documentation for android.widget.TextView.setText (int).
textView.setText (str) and textView.text = $str, does the same job of setting the specified str to TextView. The only difference I can come up with is, textView.setText (str) // old Java way of setting Text where method setText (str) was being called.
Android TextView is a user interface which displays the text to the user. A simple XML code of TextView in a layout is shown below. We can get and modify the content of text view defined in the XML layout in Kotlin class file as: The EditText is a user interface which is used for entering and changing the text.
It is used to display the text. It is used to change the color of the text. It is used to specify how to align the text by the view's x and y-axis. It is used to make the TextView be at most this many pixels wide. It is used to make the TextView be at least this many pixels wide.
They're the same in most cases, basically Kotlin generates a synthetic property for the class attributes based on their getter, which you can use to assign values to and get values from.
//So, for most cases
textView.setText("some value");
//Is the same as
textView.text = "some value"
//The second is simply shorter and is the 'kotlin way' of assigning values
In most cases, this works fine. But, as mentioned, the synthetic property is generated from the getter, if there is a setter as well, then issues arise. The reason is that the getter and the setter may have different types. For example, EditText
has Editable
getter, now, kotlin creates a synthetic property text
of the type Editable
.
editText.setText("some value"); //Works
editText.text = "some value" //Won't work, will show an error stating that expected type is Editable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With