TextView in Android

By | April 5, 2020

In this tutorial, we will learn about TextView in Android. Text view is one of the simplest widget in android. We use Text View to show some simple text to the user. You can show paragraphs using Text View or User Name etc. It totally depends upon the requirement of Activity. In this lesson, we would learn how to add a Text View in the XML layout file and how we can set text into TextView from our Java.

So without wasting time, we will directly move to our example. In this example, I would show how to add a TextView in the XML layout file.

XML Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:text="Welcome to Owlbuddy"
        android:textStyle="bold" />

In this example, you can see how added TextView in the XML layout file. In this example, we used several attributes now I will explain each attribute that why we are using them.

  • id: we are using id attribute to assign a unique id to Text View
  • width: we are using width attribute to set the width of Text View
  • height: we are using height attribute to set the height of Text View
  • layout_marginBottom we are using layout_marginBottom attribute to set margin from bottom to Text View
  • text: we are using text attribute to set text in the Text View
  • textColor: we are using textColor attribute to set the color of the text in Text View
  • textSize: we are using textSize attribute to set the size of the text in Text View
  • textStyle: we are using textStyle attribute to give style to the text of Text View. In this case, I am setting style bold to make the text thicker than usual

After looking at this XML layout file example. Let’s jump to our next example. In this example, we will see how we can set text into our Text View using Java code.

Java Code

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        LinearLayout linearLayout =  (LinearLayout) findViewById(R.id.linearlayout);
        TextView textView = new TextView(this);
        textView.setText("Welcome to Owlbuddy.com");

We have a TextView class in Java and which helps us to create TextView in our activity. In this example, you can see we are using setText message to set text in our TextView. Apart from this, you can use many other methods to make TextView better like.

  • setTextColor(): To set color of text in TextView.
  • setTextSize(): To set size of text in TextView