How to add TextView to activity and handle Android TextView click events using Kotlin
Last updated Dec 10, 2021In this Android example tutorial we will cover how to work with Textview and Textview click events. Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it.
Implementation:
First of all, open kotlin project in Android Studio.
Add a TextView in activity_main.xml file inside LinearLayout.
<TextView
android:id="@+id/text_view_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Android Developer"
android:textSize="40dp"/>
|
Add attributes in TextView like text, textColor, textSize, textStyle in the activity_main.xml file
To set the color in TextView we will use textColor property.
android:textColor="#FF6200EE" |
Here "#FF6200EE" is the code of color.
If you want to make the text Bold, Italic, normal etc. use textStyle property.
android:textStyle="bold" |
There are other properties like fontSize, fontFamily, textAlignment, letterSpacing, maxLines, minLines...
android:textSize="40dp" |
3. Now let's use our TextView inside Activity. To use any view from layout to activity by using its id property
with findViewById() method.
val textView = findViewById(R.id.text_view_id) as TextView |
Here R.id.text_view_id is the id of the textView which is defined in activity_main.xml file.
4. Now we can add event listener on TextView by implementing onClickListener to the TextView instance.
textView.setOnClickListener{ |
6. In the above code OnClick of TextView it will display a Toast of 'I am Android Developer'.
Note: Toast is a small message displayed on the screen.
7. Now run the application and you will see the below output.
Output:
Complete source code for Android TextView example:
- activity_main.xml file
< android:orientation="vertical" |
- MainActivity.kt file
import androidx.appcompat.app.AppCompatActivity |
Conclusion: We have covered how to add TextView in Android and add Click event fot the Textview with kotlin code.
Article Contributed By :
|
|
|
|
1224 Views |