ภาพรวม
ตัวอย่างนี้แสดงวิธีเปลี่ยนพื้นหลัง (Background) ของ Layout ให้เป็น Drawable resource แบบไดนามิกผ่านโค้ด Java
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: จัดทำ 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"
android:id="@+id/rl"
tools:context=".MainActivity">
<Button
android:text="ตั้งค่า Drawable"
android:id="@+id/btnSetDrawable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"/>
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.rl);
button = findViewById(R.id.btnSetDrawable);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
relativeLayout.setBackgroundResource(R.drawable.image);
}
});
}
}
เมธอดสำคัญสำหรับการตั้งค่า Background
| เมธอด | คำอธิบาย | พารามิเตอร์ |
|---|---|---|
| setBackgroundResource() | ใช้ Resource ID (@drawable/...) | int resId |
| setBackgroundDrawable() | ใช้ Drawable object (Deprecated API 22+) | Drawable |
| setBackground() | ใช้ Drawable object (API 16+) | Drawable |
| setBackgroundColor() | ใช้สี (Color int) | int color |
ตัวอย่างเพิ่มเติม
// ใช้ Drawable จาก Resources
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.my_image);
relativeLayout.setBackground(drawable);
// ใช้ Color Drawable
relativeLayout.setBackgroundColor(Color.parseColor("#FF5722"));
// ใช้ GradientDrawable สร้างเอง
GradientDrawable gd = new GradientDrawable();
gd.setColor(Color.RED);
gd.setCornerRadius(20);
gd.setStroke(2, Color.BLACK);
relativeLayout.setBackground(gd);
ขั้นตอนที่ 4: AndroidManifest.xml
Manifest มาตรฐาน ไม่ต้องเพิ่มสิทธิ์พิเศษ
การทดสอบ
เตรียมรูปภาพ image.jpg ใน res/drawable/ รันแอป กดปุ่ม พื้นหลังจะเปลี่ยนเป็นรูปนั้น