Java how to create textview programmatically in android

Java how to create textview programmatically in android

To create a TextView programmatically in Android, you can use the following steps:

  1. Import the TextView class:
import android.widget.TextView;
S‮uo‬rce:www.lautturi.com
  1. Create a new TextView object:
TextView textView = new TextView(context);

Here, context is the Context in which the TextView will be displayed, such as an Activity or a Fragment.

  1. Set the text for the TextView:
textView.setText(text);

Here, text is the string that you want to display in the TextView.

  1. Set the layout parameters for the TextView:
textView.setLayoutParams(layoutParams);

Here, layoutParams is an object of a class that extends ViewGroup.LayoutParams, such as LinearLayout.LayoutParams or RelativeLayout.LayoutParams. This specifies the layout constraints for the TextView, such as its size and position within its parent layout.

  1. Add the TextView to a layout:
parentLayout.addView(textView);

Here, parentLayout is the layout that will contain the TextView, such as a LinearLayout or a RelativeLayout.

Here's an example of a complete program that creates a TextView and adds it to a LinearLayout:

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // Create a LinearLayout
      LinearLayout linearLayout = new LinearLayout(this);
      linearLayout.setOrientation(LinearLayout.VERTICAL);

      // Create a TextView
      TextView textView = new TextView(this);
      textView.setText("Hello, world!");

      // Set the layout parameters for the TextView
      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
      textView.setLayoutParams(layoutParams);

      // Add the TextView to the LinearLayout
      linearLayout.addView(textView);

      // Set the LinearLayout as the content view
      setContentView(linearLayout);
   }
}

This will create a TextView that displays the text "Hello, world!" and adds it to a vertical LinearLayout. The LinearLayout is then set as the content view of the Activity.

Created Time:2017-11-03 22:21:05  Author:lautturi