April 23, 2020

Two methods of using text view in Android.

By Mohit Agrawal

Learn different ways of using text view.

android background

In this small tutorial, we will be covering the different ways of using text view in Android. The first way is by using text view in XML code only. The second way is to define text view in JAVA as well as XML both. I have made this easy for the beginners.

Using only XML but not JAVA

This is the simplest way of displaying your content in android UI using text view. In this, we define a text view element in XML and write our contents to be displayed.

<TextView 
 android:text="First way of creating TEXTVIEW" 
/>

Here we are using TextView element and android: text to set our text to be displayed. But the disadvantage of this method is that displayed text can not be changed once compiled. so that’s why the second method comes into the picture.

Using both JAVA as well as XML

As we have seen in the above method that once the text is defined then they can not be changed. So let’s start with the alternative method and the most commonly used method. Like the previous method, we declare text view UI in XML file but this time with unique Id to textView as shown below.

<TextView android:id="@+id/textView2" android:text="First way of creating TEXTVIEW" />

Now In Java file we will be calling this textView by its Id.

public class MainActivity extends AppCompatActivity { 
private TextView textView; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
textView = (TextView) findViewById(R.id.textView); 
textView.setText("Hi This I have done using 1st method"); 
} 
}

Like we declare integers or any variable similarly we declaring a textView variable private TextView textView; now in onCreate method we are initializing text view variable a TextView using findViewById(R.id.textView). Now use setText to set the text to text view. We are ready to see our output. Let’s run our app. 

https://www.youtube.com/watch?v=ybTC_8J0UcE