TEXTVIEW EXAMPLE

top banner

TextView Example

A TextView in XML layout in Android Studio can be used to display Text in your app. To use TextView in an XML layout in Android Studio, follow these steps:

  1. Open your XML layout file in the design editor.
  2. In the Palette panel, locate the TextView widget.
  3. Drag and drop the widget into the layout.
  4. Customize the properties of the TextView using the Properties panel. You can set the text, text size, text color, and more.
  5. Save your changes and preview the layout on an emulator or device.

Here’s an example of a simple TextView in XML:

<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp"
android:textColor="#000000" />

Note: android:textSize is set in scaled pixels (sp) and android:textColor uses an RGB hexadecimal code for the color.
Here’s an example of using TextView in Java code and adding it to an XML layout:
XML Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>

Java Code:

LinearLayout parentLayout = findViewById(R.id.parent_layout);
TextView textView = new TextView(this);
textView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setText("Hello, World!");
textView.setTextSize(24);
textView.setTextColor(Color.parseColor("#000000"));
parentLayout.addView(textView);

Note that you will need to specify the correct layout resource ID (e.g. R.id.parent_layout) in your Java code, and you should also call setContentView() to set the layout as the content view of the activity.

Leave a Reply

Your email address will not be published. Required fields are marked *