The Android TextView component is a View subclass which is capable of showing text. Being a subclass of View the TextView
component can be used in your Android app’s GUI inside a ViewGroup, or as the content view of an activity.
Creating a TextView
You can create a TextView instance either by declaring it inside a layout XML file or by instantiating it programmatically.
Below example will cover both ways of creating a TextView in the following sections.
Creating a TextView in a Layout File
Creating a TextView inside an Android layout XML file is done by inserting a TextView element into the layout file at the
place where you want the TextView to be displayed. Here is an example layout file declaring a TextView:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" android:paddingleft= "@dimen/activity_horizontal_margin" android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" android:paddingbottom= "@dimen/activity_vertical_margin" tools:context= ".MainActivity" > <textview android:text= "@string/hello_world" android:id= "@+id/textview" android:layout_width= "wrap_content" android:layout_height= "wrap_content" > </textview></relativelayout> |
Once the layout file is used as the content view of an Activity subclass you can obtain a reference to the TextView instance like this:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView) findViewById(R.id.textview); textView.setText( "Java" ); } } |
You can also instantiate an Android TextView programmatically. Here is an Android TextView instantiation example:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rootlayout); TextView textView = new TextView( this ); textView.setText( "Hey, one more TextView" ); relativeLayout.addView(textView); } } |