First you need to specify the textview id in the XML file so that it can be accessed in the Java source (note the android: id attribute in the following XML) ;
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@drawable/andriod" android:layout_gravity="center_vertical" android:gravity="center_vertical"> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
Now set the text in this text view;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView = (TextView) findViewId(R.id.textView); textView.setText("This is the first andorid app"); }
Notice how you access the text view declared in XML.
Is not
TextView textView = new TextView(this);
this will create a new text view. But here we need
TextView textView = (TextView) findViewId(R.id.textView);
this will refer to the text view specified in the XML file above.
source share