Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách thêm TextView vào LinearLayout động trong Android

Giới thiệu

Hướng dẫn này trình bày cách tạo và thêm TextView vào LinearLayout theo chương trình (dynamically) trong Android, thay vì khai báo trong XML.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical" />

Bước 3: Viết logic xử lý (src/MainActivity.java)

package app.com.sample;

import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Lấy reference đến LinearLayout container
        LinearLayout llMain = findViewById(R.id.rlMain);
        
        // Tạo TextView mới theo chương trình
        TextView textView = new TextView(this);
        textView.setText("Tôi được thêm động vào view!");
        
        // Tạo LayoutParams phù hợp với LinearLayout
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT  // Nên dùng WRAP_CONTENT cho TextView
        );
        // Có thể thêm margin
        params.setMargins(0, 16, 0, 16);
        
        textView.setLayoutParams(params);
        
        // Thêm vào LinearLayout
        llMain.addView(textView);
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Các lưu ý quan trọng

  • Phải dùng LayoutParams đúng loại với parent container (LinearLayout.LayoutParams cho LinearLayout, RelativeLayout.LayoutParams cho RelativeLayout, v.v.)
  • TextView nên dùng WRAP_CONTENT cho height thay vì MATCH_PARENT
  • Có thể thêm nhiều view liên tiếp bằng cách gọi addView() nhiều lần
  • Để chèn tại vị trí cụ thể: addView(view, index)
  • Để xóa: removeView(view) hoặc removeViewAt(index)

Ví dụ mở rộng: Thêm nhiều TextView trong vòng lặp

for (int i = 0; i < 5; i++) {
    TextView tv = new TextView(this);
    tv.setText("Dòng thứ " + (i + 1));
    tv.setTextSize(18);
    tv.setTextColor(Color.BLACK);
    llMain.addView(tv);
}

Chạy ứng dụng

Kết nối thiết bị Android, nhấn Run trong Android Studio. TextView sẽ xuất hiện trong LinearLayout trống ban đầu.

Cách thêm TextView vào LinearLayout động trong Android