Programming and Personal Development

Displaying text in a android application

There are 2 useful widgets in android for displaying text in your application.

  • TextView: This is the basic widget that can  display text to the user.  Its useful in construction of  user forms where user is hinted on the information he is expected to enter. eg: “address”, “phone no” etc. The text however is  static and cannot be directly edited by the user.
  • EditText:  This widget extends the functionality of TextView and allows the user to manipulate the text, add multiple lines of text etc.

Lets look at both the widgets  with a simple example. The desired output is as shown below:

TextView and EditText Demo

  • We first  render the TextView and EditText widgets  one below the other and initialize it with sample text.
  • We then register a “onKeyListener” to  listen for the keystrokes on the EditText widget
  • Every time the user hits the “enter” key we replace the  text in the TextView widget with the text in the EditText widget

The code snippet below  shows the implementation. The xml layout file  is used for structuring the components on the screen and the java code handles the listener logic.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=""

    <TextView android:id="@+id/textview"
              android:text="I am a non-editable text"/>

    <EditText android:id="@+id/editText"
              android:text="I am a editable text"



// Java Code for the listener logic
public class LabelDemo extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        // Get the widget references by ID
        final TextView tv = (TextView) findViewById(;
        tv.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        final EditText et = (EditText) findViewById(;
        // Add a Listener to update the textview text with the 
        // user entered input
        et.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN 
                         && keyCode == KeyEvent.KEYCODE_ENTER) {
                    boolean keyResult = v.onKeyDown(keyCode, event);
                    return keyResult;
                return false;
Web Analytics