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

Cách áp dụng Theme cho một Activity cụ thể trong Android?

Giới thiệu

Bài viết minh họa cách đặt theme riêng cho một Activity cụ thể (khác với theme toàn app) thông qua thuộc tính android:theme trong AndroidManifest.xml.

Các bước thực hiện

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

Khởi tạo project Android Studio.

Bước 2: Layout cơ bản (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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" />
</android.support.constraint.ConstraintLayout>

Bước 3: MainActivity (src/MainActivity.java)

import android.support.v7.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);
    }
}

Bước 4: Áp dụng theme Dialog cho Activity (AndroidManifest.xml)

<?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">
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.Dialog.MinWidth">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Activity hiển thị như một Dialog (có viền, không fullscreen, background mờ).

Cách áp dụng Theme cho một Activity cụ thể trong Android?

Các Theme có sẵn thường dùng cho Activity đơn lẻ

ThemeMô tả
Theme.AppCompat.DialogDialog tiêu chuẩn, có title bar
Theme.AppCompat.Dialog.MinWidthDialog width tối thiểu, phù hợp form
Theme.AppCompat.Dialog.AlertDialog kiểu Alert
Theme.AppCompat.Light.DialogDialog nền sáng
Theme.AppCompat.NoActionBarFullscreen không Action Bar
Theme.AppCompat.TranslucentTrong suốt, thấy Activity dưới
Theme.MaterialComponents.Light.DialogMaterial Design Dialog (cần MaterialComponents theme)

Tạo Custom Theme cho Activity

1. Định nghĩa trong res/values/styles.xml

<style name="MyCustomActivityTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/purple_200</item>
    <item name="colorPrimaryDark">@color/purple_700</item>
    <item name="colorAccent">@color/teal_200</item>
    <item name="android:windowBackground">@color/light_gray</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

2. Áp dụng trong Manifest

<activity android:name=".MySpecialActivity" android:theme="@style/MyCustomActivityTheme">

Áp dụng Theme bằng Code (Runtime)

// Phải gọi TRƯỚC setContentView() và super.onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.MyCustomActivityTheme); // Set theme tại runtime
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Lưu ý quan trọng

  • Theme trong <activity> ghi đè theme của <application>
  • Gọi setTheme() trước super.onCreate() và setContentView()
  • Thay đổi theme runtime gây recreate() Activity (mất state nếu không handle)
  • Dialog theme: Activity không fullscreen, có thể set android:windowIsFloating="true"
  • Material Components: Theme app phải kế thừa Theme.MaterialComponents.* thì Activity theme Material mới hoạt động đúng

Use Cases phổ biến

  • Activity setting/preferences: Theme.Dialog.MinWidth
  • Activity chọn ảnh/color picker: Theme.Translucent
  • Màn hình login/register: NoActionBar fullscreen
  • Dark/Light mode cho từng màn hình khác nhau
  • Activity in-app browser: Custom theme với toolbar riêng