Android TextView

Filed Under: Android

Android TextView is one of the very basic component and used a lot. Let’s have a deep look into TextView today.

According to the Google Documentation:

TextView class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for all widgets.

Android TextView

Android TextView class is a subclass of View class and is designed to hold and display text. It can be used in the code by importing the package android.widget.TextView. Typically, a TextView isn’t meant for editing. For editing we use EditText.
android textview

Creating a TextView in Layout

Following is the way to define a TextView in the layout file.


<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="com.journaldev.textviewexample.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</LinearLayout>
  • android:text attribute holds the string that’s to be displayed.
  • android:id attribute stores the unique identifier of the TextView. We retrieve the TextView in our Java Activity using this id.
  • In the respective activity/fragment, we call the above TextView using findViewById
    
    TextView textView = findViewById(R.id.textView);
    
  • In the present Android SDK versions, the type TextView is inferred on the right hand side. In Android SDK < 25, we have to explicitly cast the findViewById to (TextView)
  • Ideally, instead of hardcoding the string in the above xml code, we should set it in the strings.xml file and use it as : android:text="@string/app_name"

Important Attributes of TextView

Some commonly used attributes of a TextView are listed below.

  • android:textColor: To set the color of the text. Can be set as #rgb #rrggbb #aarrggbb. (aa represents the transparency, opacity. We can also set the color from colors.xml. Example : @color/colorPrimaryDark or @android:color/white
  • android:textSize: To set the size of the textView. Generally, it’s set in sp(scaled pixels). Example: 18sp.
  • android:textAllCaps : Set the boolean value. Setting true would capitalize the string.
  • android:textStyle: By default the style is normal. You can set it to bold, italic. To set one or more together use |.
  • android:maxLines : Set the maximum number of lines you want the text to be in. Setting this to 1 would make it a single line TextView.
  • android:ellipsize: This is used for truncating the text which are longer than the view rather than being broken. start adds a .. in place of the starting characters of the string. end adds them for the remaining characters. middle adds it for the middle ones. Setting marquee makes the textview slide left right continously. For marquee to work, set android:textIsSelected="true" and android:scrollHorizontally="true"
  • android:gravity: Specifies the alignment of the text by the view’s x- and/or y-axis when the string is smaller than the TextView width/height. center, start, end, center_vertical, center_horizontal.
  • android:lineSpacingMultiplier: Extra spacing between lines of text, as a multiplier. Setting 1.5 makes the spacing 1.5 times larger than the current spacing.
  • android:textAppearance : Sets a style for the text which includes it’s own color, size, font etc. We can use built-in styles or create our own in the styles.xml file.
  • android:typeface: is used to set the typeface of the text among: monospace, serif, sans, normal.
  • android:visibility: is used to set the visibility of the TextView among: visible, invisible, gone. gone is different from invisible. gone makes the TextView inivisible and makes it vanish from the layout. In invisible the TextView is still at exactly the same place.

Let’s try setting these in our activity_main.xml file in our Android Studio Project.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:id="@+id/linearLayout"
    tools:context="com.journaldev.textviewexample.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:padding="16dp"
        android:textColor="@android:color/holo_red_dark"/>

    <TextView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="Hello World!"
        android:textColor="@android:color/holo_red_dark"/>

    <TextView
        android:layout_width="match_parent"
        android:text="Hello World!"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="Hello World!"
        android:gravity="center"
        android:textAllCaps="true"
        android:textColor="@android:color/holo_green_dark"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="Hello World!"
        android:gravity="center"
        android:textStyle="bold|italic"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="Hello World!"
        android:gravity="center"
        android:typeface="sans"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="@string/long_string"
        android:gravity="center"
        android:ellipsize="end"
        android:maxLines="1"
        android:typeface="sans"
        android:textColor="#1F2124"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:text="@string/long_string_line_spacing"
        android:gravity="center"
        android:lineSpacingMultiplier="1.5"
        android:typeface="sans"
        android:textColor="@color/colorPrimary"
        android:layout_height="wrap_content" />

</LinearLayout>

We’ve set a few texts in the strings.xml file in order to avoid keeping long hardcoded strings in the layout file.

Instead of hardcoding the textSize, we can set the same in the dimens.xml file in the values folder under the resource directory.

The output of the activity with the updated layout as shown above is:

android textview xml attributes

Note: The strings.xml and dimens.xml files hold the values in the form of key-value pairs – Dictionary.

Creating a TextView Programmatically

We can create a TextView in our activity directly. We just need to initialize it, set the attributes using methods and add the TextView object into the parent layout as shown below.


package com.journaldev.textviewexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout linearLayout = findViewById(R.id.linearLayout);

        TextView textView = new TextView(this);
        textView.setText("Now we've created a TextView programmatically");
        linearLayout.addView(textView);
    }
}

To set the visibility of the TextView programmatically, we use setVisibility() and pass either View.VISIBLE or VIEW.INVISIBLE or VIEW.GONE

Setting TextView Width and Height

We can set the TextView width and height programmatically as shown below.


textView = new TextView(this);
textView.setText("This TextView has the width and height fixed");
textView.setLayoutParams(new LinearLayout.LayoutParams(50, 50));
linearLayout.addView(textView);

//set gravity too
textView = new TextView(this);
textView.setText("This TextView has the width and height set to wrap content and gravity as center");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
linearLayout.addView(textView);

Scaling Width Height in DP

In the above code, we’d set the values as an int which calculates the width and height in pixels.
Pixels can vary from screen to screen, hence we need to use density independency pixels (dp).
To set the accurate dimensions in dp as we did in xml, we need to do scaling as shown below.


final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

Eventually the pixels value should be used in the above code by passing 50 into dps


TextView textView = new TextView(this);
textView.setText("This TextView has the width and height fixed");
textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pixels));
linearLayout.addView(textView);

Setting TextView Size

We can set the size on a TextView programmatically in the following way:


final float scale = getBaseContext().getResources().getDisplayMetrics().density;
int pixels = (int) (10 * scale + 0.5f);

TextView textView = new TextView(this);
textView.setText("This TextView has the size set on the object");
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,15);

Since the TextView height in the above code is set to 10dp, the TextView displayed would be cut.

Setting TextView color Programmatically


TextView textView = new TextView(this);
textView.setText("This TextView has the text color set on the object");
textView.setTextColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
linearLayout.addView(textView);

textView = new TextView(this);
textView.setText("This TextView has the text color set on the object");
textView.setTextColor(Color.parseColor("#20808080")); //or 
linearLayout.addView(textView);


To get a color from the colors.xml we use ContextCompat(Since API>23).

To set the rgb value we use Color.parseColor()

In the above code, we’ve set transparency to 20 percent on the second TextView.

Note: We can also set textView.setTextColor(Color.RED);

The code with the above TextViews initialized in the MainActivity.java is:


package com.journaldev.textviewexample;

import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout linearLayout = findViewById(R.id.linearLayout);

        TextView textView = new TextView(this);
        textView.setText("Now we've created a TextView programmatically");
        linearLayout.addView(textView);

        textView = new TextView(this);
        textView.setText("This TextView has the width and height fixed");
        textView.setLayoutParams(new LinearLayout.LayoutParams(50, 50));
        linearLayout.addView(textView);

        final float scale = getBaseContext().getResources().getDisplayMetrics().density;
        int pixels = (int) (10 * scale + 0.5f);

        textView = new TextView(this);
        textView.setText("This TextView has the width and height fixed");
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pixels));
        linearLayout.addView(textView);

        textView = new TextView(this);
        textView.setText("This TextView has the width and height set to wrap content and gravity as center");
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setGravity(Gravity.CENTER);
        linearLayout.addView(textView);

        textView = new TextView(this);
        textView.setText("This TextView has the size set on the object");
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        linearLayout.addView(textView);
        //or
        //textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.textSize));

        textView = new TextView(this);
        textView.setText("This TextView has the text color set on the object");
        textView.setTextColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
        linearLayout.addView(textView);

        textView = new TextView(this);
        textView.setText("This TextView has the text color set on the object");
        textView.setTextColor(Color.parseColor("#20808080"));
        linearLayout.addView(textView);
    }

}

The output when the above code was run is :
android textview setText programmatically

The programmatically created TextViews are added beneath the xml ones in the LinearLayout since the orientation was vertical.

Drawable With TextView

We can define a TextView with a drawable to it’s left/right/top/bottom.


<TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:gravity="center"
        android:drawableLeft="@mipmap/ic_launcher"
        android:drawablePadding="16dp"
        android:textColor="@android:color/holo_red_dark"/>

android textview drawable padding

Setting a Custom Font on TextView

We can set a custom font .ttf or .otf typeface file on the TextView by first creating an assets directory under src | main folder in our Android Studio Project.

Now we’ve added a .ttf file in the assets folder. Our project structure looks like this:

android textview project structure


textView = new TextView(this);
textView.setText("This TextView has Roboto font");
textView.setTypeface(Typeface.createFromAsset(getAssets(),"Roboto-Bold.ttf"));
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
linearLayout.addView(textView);

setTypeface() is used to set the custom font, it takes the getAssets() folder to invoke the assets directory.

The second parameter is the path to the font file. Since in our case it is present in the root directory, the path is simply the filename.

The output looks like this:
android textview custom font

Notice the latter TextView with a custom font!

Click Listener on TextView

We can trigger something when the TextView is click using the setOnClickListener on the TextView object.


<TextView
    android:id="@+id/textViewClickable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name" 
    android:clickable="true"/>

For a TextView to have click functionality, we need to add the android:clickable as true in the xml.

In the MainActivity.java onCreate method we do the following.


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView textViewClickable = findViewById(R.id.textViewClickable);
textViewClickable.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               textViewClickable.setTextColor(Color.ORANGE);
            }
        });

}

Alternative method using xml attribute android:onClick


<TextView
    android:id="@+id/textViewClickable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name" 
    android:clickable="true"
    android:onClick="methodName"/>

Using onClick we set the method name to be invoked in the Java class whenever the TextView is clicked.


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView textViewClickable = findViewById(R.id.textViewClickable);

}

public void methodName(){
textViewClickable.setTextColor(Color.ORANGE);
}

Displaying Html in a TextView

We can display html code in a TextView as shown below.


textView.setText(Html.fromHtml(
"<p><b>JournalDev.com</b> Android TextView Tutorial</p>"));

autoLink attribute

The autoLink attribute is used to detect a certain pattern in the TextView among the following:

  • web
  • map address
  • email address
  • phone
  • all

It converts the matched pattern string into a link. And on clicking the link the relevant behavior happens(opens browser for web, calling for phone, gmail for email, google maps for maps)

Let’s replace one of our TextViews to the following:


<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:text="Hello World! www.journaldev.com"
        android:textColor="@android:color/holo_red_dark"/>

The output with above TextView in the layout is given below:
android textview

This brings an end to Android TextView tutorial. You can download the project from the link below.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages