การใช้ Theme แบบเฉพาะ Activity (Per-Activity Theme) ใน AndroidManifest
ตัวอย่างนี้แสดงวิธีกำหนด Theme ให้ Activity เฉพาะตัว โดยใช้ attribute android:theme ในแท็ก <activity> แทนที่จะกำหนดที่ Application Level
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → กรอกรายละเอียด → Finish
ขั้นตอนที่ 2: Layout - res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
ขั้นตอนที่ 4: AndroidManifest.xml - ใช้ Theme เฉพาะ Activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<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"> <!-- Default Theme สำหรับทั้งแอป -->
<activity
android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.Dialog.MinWidth"> <!-- Theme เฉพาะ Activity นี้ -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Theme สำเร็จรูปที่นิยมใช้ต่อ Activity
| Theme | ลักษณะ | ใช้เมื่อไหร่ |
|---|---|---|
| Theme.AppCompat.Dialog | Dialog ธีม มุมโค้ง มีเงา | Activity แบบ Dialog/Modal |
| Theme.AppCompat.Dialog.MinWidth | Dialog กว้างเต็มจอ (Min Width) | Bottom Sheet, Full-width Dialog |
| Theme.AppCompat.Dialog.Alert | Alert Dialog ธีม | Confirmation Dialog |
| Theme.AppCompat.Light.NoActionBar | Light Theme ไม่มี Action Bar | Full Screen Activity |
| Theme.AppCompat.DayNight.NoActionBar | รองรับ Dark Mode | แอปที่มี Dark/Light Theme |
| Theme.MaterialComponents.Light.Dialog | Material Design Dialog | Material Design 3 |
| Theme.Translucent.NoTitleBar | โปร่งใส ไม่มี Title | Overlay, Splash Screen |