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

Cách đặt chiều rộng và cao ImageView theo chương trình trên Android bằng Kotlin

Giới thiệu

Ví dụ minh họa cách tạo ImageView hoàn toàn bằng code Kotlin, thiết lập kích thước (width/height) và thêm vào RelativeLayout cha.

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

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

Android Studio > File > New Project.

Bước 2: Layout (activity_main.xml) - Chỉ có container

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    tools:context=".MainActivity">
</RelativeLayout>

Bước 3: MainActivity.kt - Tạo ImageView động

import android.os.Bundle
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val relativeLayout: RelativeLayout = findViewById(R.id.relativeLayout)
        val imageView = ImageView(this)
        imageView.setImageResource(R.drawable.image) // Cần có drawable tên "image" trong res/drawable

        // Thiết lập LayoutParams cho ImageView
        val params = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, // Chiều rộng = match_parent
            RelativeLayout.LayoutParams.MATCH_PARENT  // Chiều cao = match_parent
        )
        imageView.layoutParams = params

        // Thêm vào ViewGroup cha
        relativeLayout.addView(imageView)
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.imageviewsize">

    <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

Chạy app, ImageView sẽ lấp đầy toàn bộ RelativeLayout (trừ padding 4dp) và hiển thị drawable R.drawable.image.

Các kiểu LayoutParams phổ biến

ViewGroup ChaLayoutParams ClassThuộc tính chính
LinearLayoutLinearLayout.LayoutParamsweight, gravity
RelativeLayoutRelativeLayout.LayoutParamsaddRule (BELOW, ALIGN_PARENT_START, ...)
ConstraintLayoutConstraintLayout.LayoutParamsconstraintSet, bias, chain
FrameLayoutFrameLayout.LayoutParamsgravity
GridLayoutGridLayout.LayoutParamscolumnSpec, rowSpec

Các cách thiết lập kích thước

// 1. Match Parent / Wrap Content (Hằng số)
val params = ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.WRAP_CONTENT
)

// 2. Kích thước cố định pixel (px)
val params = ViewGroup.LayoutParams(300, 200) // width=300px, height=200px

// 3. Kích thước DP (Chuyển đổi)
val dp100 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100f, resources.displayMetrics).toInt()
val params = ViewGroup.LayoutParams(dp100, dp100)

// 4. Margin (chỉ áp dụng cho MarginLayoutParams subclass)
val params = RelativeLayout.LayoutParams(...).apply {
    setMargins(16, 16, 16, 16) // left, top, right, bottom (px)
    // Hoặc
    marginStart = dpToPx(16)
    marginEnd = dpToPx(16)
}

Cách hiện đại: ViewBinding / DataBinding

Thay vì findViewById và tạo view thủ công, dùng ViewBinding:

// build.gradle: buildFeatures { viewBinding = true }
// Activity
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    // binding.relativeLayout.addView(imageView) // Dùng binding
}

Lưu ý

    Phải dùng LayoutParams đúng loại với ViewGroup cha (RelativeLayout -> RelativeLayout.LayoutParams). Sai loại sẽ crash hoặc layout sai.
  • addView() thêm view vào cuối. Dùng addView(view, index) để chèn vị trí cụ thể.
  • Để xóa: parent.removeView(child) hoặc parent.removeAllViews().
  • ImageView scaleType: centerCrop, fitCenter, centerInside, v.v. để kiểm soát hiển thị ảnh trong khung.