Giới thiệu
Bài viết này minh họa cách thêm TextView vào LinearLayout một cách động (programmatically) trong Android sử dụng Kotlin.
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 đầy đủ thông tin để tạo dự án mới.
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"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/linearLayout"
android:padding="16sp"
tools:context=".MainActivity">
</LinearLayout>
Bước 3: Viết logic xử lý (src/MainActivity.kt)
import android.graphics.Color
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val linearLayout: LinearLayout = findViewById(R.id.linearLayout)
val textView = TextView(this)
textView.text = "Tôi được thêm động vào view"
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
textView.layoutParams = params
textView.textSize = 24F
textView.setTextColor(Color.RED)
linearLayout.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="com.example.q11">
<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>
Chạy ứng dụng
Kết nối thiết bị Android thực với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn và kiểm tra màn hình hiển thị.
Mẹo: DùngLayoutParams.WRAP_CONTENTcho chiều cao nếu không muốn full screen. Có thể thêm margin:params.setMargins(16, 16, 16, 16). Để xóa view:linearLayout.removeView(textView)hoặclinearLayout.removeAllViews().