Android/Java สร้าง TextView แบบ programmatically

ไฟล์ที่เกี่ยวข้อง

  • activity_main.xml
  • MainActivity.java

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/layoutMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.phaisarn.myapplication;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // creating TextView programmatically
        TextView textView = new TextView(this);
        textView.setTextSize(20f);
        textView.setText("This is a dynamic TextView generated programmatically in Java");

        // add TextView to LinearLayout
        LinearLayout layoutMain = findViewById(R.id.layoutMain);
        layoutMain.addView(textView);
    }
}

บรรทัดที่ 22 : ถ้างถึง LinearLayout
บรรทัดที่ 23 : เอา textView ใส่เข้าไปใน LinearLayout