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

Cách đặt vị trí tuyệt đối (absolute position) cho View trong Android Kotlin

Ví dụ này minh họa cách thêm View vào RelativeLayout với vị trí tuyệt đối (leftMargin, topMargin) bằng Kotlin.

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

Tạo dự án mới trong Android Studio, chọn Kotlin.

Bước 2: Layout (res/layout/activity_main.xml)

<?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"
    tools:context=".MainActivity">
</RelativeLayout>

Bước 3: MainActivity.kt

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)
        
        val relativeLayout = findViewById(R.id.relativeLayout)
        val imageView = ImageView(this).apply {
            setImageResource(R.drawable.image)
        }
        
        // LayoutParams: width=600px, height=800px, leftMargin=100px, topMargin=300px
        val params = RelativeLayout.LayoutParams(600, 800).apply {
            leftMargin = 100
            topMargin = 300
        }
        
        relativeLayout.addView(imageView, params)
    }
}

Lưu ý: Đơn vị là pixel. Để dùng dp, hãy convert: TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100f, resources.displayMetrics).toInt().

Bước 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.q1">
    <application ...>
        <activity android:name=".MainActivity">...</activity>
    </application>
</manifest>

Chạy ứng dụng

ImageView xuất hiện tại tọa độ (100, 300) với kích thước 600x800px.

Cách đặt vị trí tuyệt đối (absolute position) cho View trong Android Kotlin