- Android TextView Using Kotlin – A Comprehensive Tutorial
- Android Tutorial
- Android TextView Overview
- Creating TextView in XML Layout
- TextView XML Attributes
- Creating Android TextView using Kotlin
- Handling Null Values in TextView Kotlin Code
- Kotlin Android Extensions
- Android TextView Kotlin onClick Listener
- Android TextView extension functions
- Android TextView “with” expression
- Creating a TextView Programmatically in Kotlin
- Using Spannable Strings
- Tutorialwing
- Output
- Video Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- Using TextView in Kotlin
- Different Attributes of TextView in XML
- Set Id of TextView
- Set Width of TextView
- Set Height of TextView
- Set Padding of TextView
- Set Margin of TextView
- Set Background of TextView
- Set Visibility of TextView
- Set Text of TextView
- Set Color of Text in TextView
- Set Gravity of TextView
- Set Text in Uppercase, Lowercase
- Set text in uppercase
- How do we set text in lowercase?
- Set Size of Text in TextView
- Set Style (Bold/italic) of Text in TextView
- Set Letter Spacing of Text in TextView
- Set Typeface of Text in TextView
- Set fontFamily of Text in TextView
- Different Attributes of Android TextView Widget
- Advance Concepts in Android TextView Using Kotlin
- Using Custom Font in TextView
- Set Ellipsis Text in TextView
- Create Shadow of Text in TextView
- Set Click Listener in TextView
- Set Ripple Effect in TextView
- Detecting And Making URL clickable in Text in TextView
- Show html in TextView
- Set Color in html Text in TextView
- Show Image in TextView
- Using span to Style text in TextView
- Creating Clickable text using span in textView
- Making text scrollable in TextView
Android TextView Using Kotlin – A Comprehensive Tutorial
Android Tutorial
Kotlin is the official programming language for Android apps development. In this tutorial, we’ll be discussing TextViews in Android applications using Kotlin programming. We’ll create and change TextViews code in Kotlin programming.
Android TextView Overview
Android TextView is a subclass of the View class. The View class typically occupy our window. TextView is used to display text on the screen. We can do a lot of fancy things using TextView.
Let’s start with a fresh project in Android Studio.
Create a new project and make sure you’ve enabled Kotlin in the setup wizard.
Creating TextView in XML Layout
TextView is created in an xml layout in the following manner.
The four attributes defined above are the core attributes of the TextView widget.
- The id property is used to set a unique identifier. It’s set as @+id/ followed by the name you assign. The same name would be used to retrieve the TextView property in our Kotlin Activity class.
- The text property is used to set the string text to be displayed in the TextView.
- As it is evident from the names itself, layout_width and layout_height are used to set the boundaries of the TextView. The wrap_content means wrapping the width, height to the length of the text. The match_parent means the TextView matches the width/height of the enclosed parent view. We can also set hardcoded values in dp (device independent pixels).
Clean Code Tips: Instead of hardcoding the string, define it inside the strings.xml and set the text in the layout as follows.
Let’s apply some attributes over the TextView in XML.
TextView XML Attributes
Let’s give you a quick tour of some of the popular attributes of TextView widget.
- android:textSize : sets the size of the TextView. It’s recommended to use sp instead of dp. The sp stands for scale independent pixels and scales the font. Example: 16sp.
- The android:textColor is used to set a color for the text. Typically it is of the format #rgb, #rrggbb, #aarrggbb.
- The android:background attribute is used to set the background color of the TextView.
- The android:textStyle is used to set the style among bold, italic, and normal. If you want to set bold and italic, use android:textStyle = “bold|italic”.
- The android:textAppearance attribute is used to set the style on a TextView, which includes its own color, font, and size. We can create custom styles in the styles.xml file.
- android:visibility is used to set the visibililty of the text, possible values are visible , invisible , and gone . The gone makes the textview invisible and removes it from the current position in the layout.
- The android:ellipsize is used to handle situations when the length of the text exceeds the limit.
.
Let’s use the xml attributes on a TextView in our layout.
Note: We’ve replaced the ConstraintLayout with a LinearLayout to make things easier.
Notice the opacity in the last TextView
For more info on XML attributes for Android TextView, visit the Google docs attached at the end of this page or JournalDev Android TextView tutorial.
In the following section, we’ll create TextView programmatically using Kotlin and set Kotlin functions, properties, and use lambda functions over the TextView.
Creating Android TextView using Kotlin
We can get the TextView in our MainActivity.kt Kotlin class using findViewById .
The findViewById is used to get a view from the XML in the Activity class using the id specified. It works like a dictionary – key/value pair.
Code Explanation:
- MainActivity Kotlin class extends AppCompatActivity.
- We’ve created the textView property by using findViewById . Though from Android API > 24 you can ignore specifying the type explicitly.
- The text property is used as getter/setter on the TextView. It returns a CharSequence.
- $
implcitily converts the CharSequence to a String. - The text property in Kotlin is equivalent to getText() and setText(String) in Java.
- To set the string from the strings.xml file, we call resources.getString(R.string. ) . The resources property is equivalent to getResources() from Java.
Handling Null Values in TextView Kotlin Code
Kotlin has a very safe way to deal with null values. Optional Types act as a wrapper over the current type. They need to be safely unwrapped to use non-null values, thus enabling null safety in our Kotlin code.
Let’s look at how the above app behaves when the textView is null.
So when the text is null, the compiler ignores it.
When the textView is null, we need to add a safe call to unwrap the textView. This way Kotlin automatically gives us null safety.
What if the textView is null at runtime?
It will throw error message as IllegalStateException. TextView cannot be null. .
So let’s set the TextView properties as Optional in the declaration.
We’ve set otherTextView to the type TextView .
So calling anything over the TextView would require a safe call.
What if the text is null? What do we display instead?
We use the elvis operator ?: from Kotlin for null safety.
In the above code, NA gets displayed if otherTextView?.text is null.
The safe call can be replaced by a let lambda expression too.
Kotlin Android Extensions
Thanks to apply plugin: ‘kotlin-android-extensions’ in our build.gradle file, we can directly bind views from the layout in our Kotlin activity class.
Add the following import statement in your MainActivity.kt class.
Now you can use the TextView properties directly without using findViewById.
Android TextView Kotlin onClick Listener
In the above code, for the setOnClickListener we use lambda expressions from Kotlin. It makes the code shorter and easier to read than Java.
To make the textViewEllipsize slide, set it to MARQUEE. To make it loop continuously, we’ve set marqueeRepeatLimit to -1.
The mipMapDrawable is of the type Drawable and setCompoundDrawablesWithIntrinsicBounds() is the equivalent of android:drawablePadding .
The app output is shown in the following GIF.
Android TextView extension functions
We can create Kotlin extension functions on a TextView to add our custom functions and properties.
The below extension function creates a consistent property for currentTextColor property and setTextColor() function.
Add the following code outside the class.
We can then set the color on our TextView using the textColor property.
Android TextView “with” expression
Instead of using redundant lines where we set the attributes on the same TextView property like this:
We can make it better using the with expression.
Creating a TextView Programmatically in Kotlin
Below, we’ve created two TextViews programmatically. We’ve set a custom font from the assets folder and set underline on one of the TextViews. Also, we’ve set the string in the form of HTML.
The assets directory is created under src | main folder and is used to hold the TTF files for the custom fonts.
Kotlin properties are required to be initialized there itself. If it’s not possible, we can set a lateinit modifier to the property.
By default, when the textView is created programmatically, its width is match_parent and height is wrap_content .
The paintFlags is used to add an underline to the string.
The output with the above TextViews added into the layout programmatically is shown in the following image.
Using Spannable Strings
Spannable Strings are useful when we have to set different styles on different substrings of the TextView.
This brings an end to the comprehensive tutorial on Android TextViews using Kotlin programming.
Источник
Tutorialwing
In this article, we will learn about android Textview using Kotlin. We will go through various example that demonstrates how to use different attributes of textView. For example, making text of textView clickable, change textStyle to bold, italic. etc.
In this article, we will get answer to questions like –
- What is TextView?
- Why should we consider TextView while designing ui for any app?
- What are possibilities using TextView while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Android TextView Using Kotlin Output
Android TextView Using Kotlin Output
Video Output
Getting Started
We can define android Textview widget as below –
Android TextView widget is a View that are used to show texts to the user and optionally allow them to edit it. However, Text editing is disabled by default. You need to customise the basic class of TextView Widget to make it editable.
Now, how do we use TextView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as TextView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android TextView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access TextView in Kotlin file without using findViewById() method.
Using TextView in Kotlin
Follow steps below to use TextView in newly created project –
- Open res/layout/activity_main.xml file. Then, add below code in it –
Notice that we already have a TextView widget in xml file. Whenever we create any android application, a TextView widget is automatically added like this in xml file.
Here, basic TextView is –
android:layout_width sets width of textView.
android:layout_height sets height of textView.
android:text sets text in textView.
We can also access it in Kotlin File, MainActivity.kt, as below –
Here, we have accessed textView as binding.textViewID.
Now, run this application. You will get output like below –
Sample App Output
There are many other things we can do with android textView using kotlin. Here, we will mostly use xml attributes to perform task in textView. However, We can also learn to use textView programmatically.
Different Attributes of TextView in XML
Let’s check how to use different attributes in textView to customise it –
Set Id of TextView
Many a time, we need id of View to access it in Kotlin file or create ui relative to that view in xml file. So, we can set id of textView using android:id attribute like below –
Here, we have set id of TextView as textView using android:id=”” attribute. So, if we need to reference this TextView, we need to use this id – textView.
Learn to Set ID of TextView Dynamically
Set Width of TextView
We use android:layout_width=”” attribute to set width of textView.
We can do it as below –
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of TextView Dynamically
Set Height of TextView
We use android:layout_height=”” attribute to set height of textView.
We can do it as below –
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of TextView Dynamically
Set Padding of TextView
We use android:padding=”” attribute to set padding of textView.
We can do it as below –
Here, we have set padding of 10dp in textView using android:padding=”” attribute.
Learn to Set Padding of TextView Dynamically
Set Margin of TextView
We use android:layout_margin=”” attribute to set margin of textView.
We can do it as below –
Here, we have set margin of 10dp in textView using android:layout_margin=”” attribute.
Learn to Set Margin of TextView Dynamically
Set Background of TextView
We use android:background=”” attribute to set background of textView.
We can do it as below –
Here, we have set background of color #ff0000 in textView using android:background=”” attribute.
Learn to Set Background of TextView Dynamically
Set Visibility of TextView
We use android:visibility=”” attribute to set visibility of textView.
We can do it as below –
Here, we have set visibility of textView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of TextView Dynamically
Set Text of TextView
We use android:text=”” attribute to set text of textView.
We can do it as below –
Here, we have set text (“Hello Tutorialwing”) in textView using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of TextView Dynamically
Set Color of Text in TextView
We use android:textColor=”” attribute to set color of text in textView.
We can do it as below –
Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in textView using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of TextView Dynamically
Set Gravity of TextView
We use android:gravity=”” attribute to set gravity of text in textView.
We can do it as below –
Here, we have set gravity of text in textView using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of TextView Dynamically
Set Text in Uppercase, Lowercase
If we need to show text of TextView in uppercase or lowercase etc.
Set text in uppercase
We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –
Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in textView.
By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,
Above code will set Hello Tutorialwing to textView.
How do we set text in lowercase?
- In xml file – write all the text in lowercase.
- In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to textView.
Set Size of Text in TextView
We use android:textSize=”” attribute to set size of text in textView.
We can do it as below –
Here, we have set size of text in textView using android:textSize=”” attribute.
Learn to Set Size of Text in TextView Dynamically
Set Style (Bold/italic) of Text in TextView
We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in textView.
We can do it as below –
Here, we have set style of text in textView using android:textStyle=”” attribute. This attribute can take bold, italic or normal.
Set Letter Spacing of Text in TextView
We use android:letterSpacing=”” attribute to set spacing between letters of text in textView.
We can do it as below –
Here, we have set spacing between letters of text in textView using android:letterSpacing=”” attribute.
Learn to Set Letterspacing of TextView Dynamically
Set Typeface of Text in TextView
We use android:typeface=”” attribute to set typeface in textView.
We can do it as below –
Here, we have set typeface of text in textView using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of TextView Dynamically
Set fontFamily of Text in TextView
We use android:fontFamily=”” attribute to set fontFamily of text in textView.
We can do it as below –
Here, we have set fontFamily (Here, sans-serif) of text in textView using android:fontFamily=”sans-serif” attribute.
Till now, we have see how to use android textView using Kotlin. We have also gone through different attributes of TextView to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android TextView Widget
Below are the various attributes that are used to customise android TextView Widget. However, you can check the complete list of attributes of Textview in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:autoLink | This attribute is used to automatically detect url or emails and show it as clickable link. |
2 | android:autoText | Use this attribute if you want to automatically correct spelling errors in text of the Textview. |
3 | android:capitalize | If it is set, it means Textview has a textual input method and should automatically capitalize whatever the user types in the Textview. |
4 | android:id | This attribute is use to provide unique ID to the Textview widget. |
5 | android:cursorVisible | Use this attribute to make cursor visible or invisible. Default is visible. |
6 | android:drawableBottom | Sets drawable(images etc.) below the text of the Textview. |
7 | android:drawableEnd | Sets drawable(images etc.) to end of text in the Textview. |
8 | android:drawableLeft | Sets drawable(images etc.) to left of text in the Textview. |
9 | android:drawablePadding | Sets padding to the drawable(images etc.) in the Textview. |
10 | android:drawableRight | Sets drawable(images etc.) to right of text in the Textview. |
11 | android:drawableStart | Sets drawable(images etc.) to start of text in the Textview. |
12 | android:drawableTop | Sets drawable(images etc.) to top of text in the Textview. |
13 | android:ellipsize | Use this attribute when you want text to be ellipsized if it is longer than the Textview width. |
14 | android:ems | Sets width of the Textview in ems. |
15 | android:gravity | Use to align text of the Textview vertically or horizontally or both. |
16 | android:height | Use to set height of the Textview. |
17 | android:hint | Use to show hint when there is no text. |
18 | android:inputType | Use to set input type of the Textview. It can be Number, Password, Phone etc. |
19 | android:lines | Use to set height of the Textview by number of lines. |
20 | android:maxHeight | Sets maximum height of the Textview. |
21 | android:minHeight | Sets minimum height of the Textview. |
22 | android:maxLength | Sets maximum character length of the Textview. |
23 | android:maxLines | Sets maximum lines Textview can have. |
24 | android:minLines | Sets minimum lines Textview can have. |
25 | android:maxWidth | Sets maximum width Textview can have. |
26 | android:minWidth | Sets minimum lines Textview can have. |
27 | android:text | Sets text of the Textview |
28 | android:textAllCaps | Use this attribute if you want to show all texts of the Textview in capital letters. |
29 | android:textColor | Sets color of the text. |
30 | android:textSize | Sets font size of the text. |
31 | android:textStyle | Sets style of the text. For example, bold, italic, bolditalic. |
32 | android:typeface | Sets typeface of the text. For example, normal, sans, serif, monospace. |
33 | android:width | Sets width of the TextView. |
We have seen different attributes of textView and how to use it. If you wish to visit post to learn more about it
Advance Concepts in Android TextView Using Kotlin
Till Now, we have seen how to use textView in android project. how to use different attributes to customize it. Now, we will go through some advance concepts in Android TextView Using Kotlin. For example, ellipsize text, clickable text, custom font in textView Widget.
Using Custom Font in TextView
Till now, we have seen how to use predefined fonts in textView. Now, we will see how to use custom fonts in textView. Follow steps below to set custom font –
- At first, get the custom font you want to use in textView. We want to set Chantelli_Antiqua font in textView. So, download it from link provided.
- Now, create assets folder inside src/main folder. Then, create fonts folder inside src/main/assets folder. Then, move Chantelli_Antiqua.ttf file inside …/fonts folder.
- Now, write below code in MainActivity.kt file.
Above line gets font from ttf file and set in textView.
Finally, MainActivity.kt file contains below code –
In activity_main.xml file, we have below code –
When you run app, output will be like –
TextView using Chantelli_Antiqua font
Set Ellipsis Text in TextView
Have you ever needed ellipsis text in textView? Or, you don’t want to show all texts in long sentence in textView ? In textView, you can set such long sentence as ellipsis text.
Follow steps below to set ellipsis text in textView –
- Add below line in textView to ellipsize text in it –
- So, open activity_main.xml file and add below code in it –
- Run the app. We will get output like below –
We can set different value for android:ellipsize=”” attribute – start, middle, end etc. We have shown above output accordingly.
Create Shadow of Text in TextView
Sometimes we want to show shadow in text inside textView. We can follow below steps to do it –
- Add below line in TextView to show shadow in text –
- Open activity_main.xml file and add below code in it –
Set Click Listener in TextView
Follow step below to set click listener in textView –
- Open activity_main.xml file. Then, write below code in it –
Here, we have used android:onClick=”” attribute to set click listener. Now, we will define onClick method in MainActivity.kt file to perform action when textView is clicked.
Open MainActivity.kt file. Then, add below code in it –
Now, run the app. A toast message is shown when textView is clicked.
Set Ripple Effect in TextView
We have already set click listener in textView. Now, follow step below to set ripple effect in textView –
- Set background as below in textView –
- Then, run the app. Whenever textView is clicked, it shows ripple effect.
Detecting And Making URL clickable in Text in TextView
Sometimes we want textView to auto detect url present in textView. Also, we want url to be clickable. Follow steps below to do that –
- We can use two attributes – android:autoLink=”” and android:linksClickable=”” in textView. Open activity_main.xml file. Then, add below code in it –
Run the app. You will notice that text https://www.tutorialwing.com is underlined and clickable.
Show html in TextView
How can we show html in textView?
Sometimes we want to style text using html format. Then, set styled text in textView. In Kotlin, we can do it as below –
- We can set html in textView using Html.fromHtml() method –
Set Color in html Text in TextView
We can write as below to set text color in html for textView –
Here, we have used Text to color to set color.
Show Image in TextView
We can show image in textView using drawableEndCompat=”” or drawableStartCompat=”” attributes.
- Open activity_main.xml file. Then, add below code in it –
Now, run app. We will get output like below –
Using span to Style text in TextView
We can use span to style text as below –
Creating Clickable text using span in textView
Sometimes we want to set text using span. While doing so, we also want to set partial text as clickable. We can do it as below –
- Create a file PatternEditableBuilder.kt in com.tutorialwing.textview package. Then, add below code in it –
- Then, add below code in MainActivty.kt file –
Making text scrollable in TextView
Follow steps below to make text scrollable in textView if text is too long –
- Use attribute android:scrollbars=”vertical” in Textview in xml file (i.e. in activity_main.xml file).
- Then, write below code in MainActivity.kt file –
- Now, run app. We will see text as scrollable text if it is too long and go outside screen
Thus, we have seen what is textView, how can we use android textview using Kotlin ? etc. We also went through different attributes of android textview.
Источник