To create a TextView programmatically in Android, you can use the following steps:
TextView class:import android.widget.TextView;Suorce:www.lautturi.com
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.
TextView:textView.setText(text);
Here, text is the string that you want to display in the TextView.
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.
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.