Android Application Development: TextView

Guest Posts Omar Shehab

This article explains displaying text on the Android screen using TextView.
Android:

In this article I’ll discuss two important and essential things required to build Android application.


  1. The java code to display the text in a TextView.

  2. The XML code to build the TextView in the Android screen.


The code for setting the text in TextView listed below:

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //cast the xml textToView item into TextView
        textView = (TextView) findViewById(R.id.textToView);
        //set the text
        textView.setText("I have new text");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}




Java Swing:

Add the following code to activitymain.xml file to create TextView element which will get its value from the java code.

<TextView

android:id="@+id/textToView"

android:layout
width="wrapcontent"

android:layout
height="wrapcontent"

android:layout
alignParentTop="true"

android:text="" />

XML code explanation

android:id="@+id/textToView" | identify the TextView

android:layoutwidth="wrapcontent" | make the TextView big enough to enclose its content

layout_alignParentTop="true" | makes the top edge of this view match the top edge of the parent

android:text=""  | initial value of the TextView is empty

Output:


Java Spring Framework:

Thanks.