บทความนี้จะสาธิตวิธีการสร้าง ListView ที่มีมุมโค้งมน (rounded corners) ในแอปพลิเคชัน Android โดยใช้ไฟล์ Drawable resource เพื่อกำหนดรูปร่างพื้นหลัง
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project แล้วกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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">
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
เพิ่มโค้ดต่อไปนี้ในไฟล์ src/MainActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
String[] fruits = new String[]{"Mango", "Apple", "Grapes", "PineApple", "Banana", "Kiwi", "Orange", "Avocado", "Strawberry"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fruits);
listView.setAdapter(adapter);
// เรียกใช้ drawable resource สำหรับมุมโค้งมน
listView.setBackgroundResource(R.drawable.rounded_corners);
}
}
ขั้นตอนที่ 4: สร้าง Drawable Resource สำหรับมุมโค้งมน
สร้างไฟล์ rounded_corners.xml ในโฟลเดอร์ res/drawable/ และเพิ่มโค้ดต่อไปนี้:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="#C0C0C0"
android:startColor="#808080" />
<corners
android:bottomLeftRadius="16dp"
android:bottomRightRadius="16dp"
android:topLeftRadius="16dp"
android:topRightRadius="16dp" />
<stroke
android:width="1px"
android:color="#000000" />
</shape>
คำอธิบาย:
<corners>- กำหนดรัศมีของมุมทั้ง 4 มุม (16dp)<gradient>- สร้างพื้นหลังแบบไล่สีจากสีเทาเข้ม (#808080) ไปสีเทาอ่อน (#C0C0C0)<stroke>- เพิ่มเส้นขอบสีดำ ความกว้าง 1px
ขั้นตอนที่ 5: ตรวจสอบ AndroidManifest.xml
ไฟล์ Manifest มาตรฐาน ไม่ต้องแก้ไขเพิ่มเติมสำหรับฟีเจอร์นี้
ทดสอบการทำงาน
รันแอปพลิเคชันบนอุปกรณ์จริงหรือ Emulator จะเห็น ListView พร้อมมุมโค้งมนและพื้นหลังไล่สีตามที่กำหนด