Sachin Ware Sachin Ware - 4 months ago 25
Android Question

How to create simple Android TextView and display text on it using java code?

Hello everyone I am a self learner of Android development. Until now I have been able to create a sample project and run Hello Android Application in Eclipse. I have come to know that Textview can be created in two way. ie.1 using xml tag and 2. using Java code.
By default I have one Textview saying Hello world in my sample project. I want to create a text view using Java code and display some message on it.
I have searched a lot, but unable to understand the steps and layout setting mentioned in the code.

This is what I have done:

import android.view.Menu;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View;

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {

LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F);

TextView tx= new TextView(this);
// tx.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tx.setText("ANDROID APP");


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


Further I don't know how to add this textview in

This is my activity_main.xml

<RelativeLayout xmlns:android=""
tools:context=".MainActivity" >


A step by step solution would be helpful for me and any good tutorial link would be appreciable. Thank you in advance!


Use this code, Create text view and set layout params

TextView dynamicTextView = new TextView(this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dynamicTextView.setText(" Hello World ");

add this textview to the main layout