บทนำ
ตัวอย่างนี้สาธิตวิธีการกำหนดระยะขอบ (margin) ของ ImageView แบบโปรแกรมมัติใน Android ด้วยภาษา Kotlin โดยไม่ต้องแก้ไขไฟล์ XML layout
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project กรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ Layout (activity_main.xml)
เพิ่มโค้ดต่อไปนี้ในไฟล์ 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด Kotlin (MainActivity.kt)
เพิ่มโค้ดต่อไปนี้ในไฟล์ src/MainActivity.kt:
import android.os.Bundle
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
val layoutParams = imageView.layoutParams as RelativeLayout.LayoutParams
layoutParams.setMargins(100, 100, 100, 100) // กำหนด margin ทุกด้าน 100 px
imageView.layoutParams = layoutParams
}
}
ขั้นตอนที่ 4: ตรวจสอบ AndroidManifest.xml
ตรวจสอบว่าไฟล์ androidManifest.xml มีการประกาศ Activity หลักอย่างถูกต้อง:
<?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>
การทดสอบ
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run เลือกอุปกรณ์ของคุณ แล้วสังเกตผลลัพธ์บนหน้าจอ
