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

Cách đặt độ trong suốt (opacity/alpha) cho View trong Android

Hướng dẫn này minh họa cách thay đổi độ trong suốt của View (TextView, Button, Layout...) bằng View.setAlpha() hoặc ObjectAnimator cho hiệu ứng mượt.

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

Mở Android Studio, chọn File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#011ffd"
        android:gravity="center"
        android:text="TextView Demo Alpha"
        android:textColor="#FFFFFF"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        android:text="Giảm độ mờ (Alpha = 0.6)" />

</RelativeLayout>

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

package com.example.sample;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView txtView;
    Button btnAlpha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtView = findViewById(R.id.textView1);
        btnAlpha = findViewById(R.id.button1);

        // Cách 1: Thiết lập trực tiếp ( tức thì)
        // txtView.setAlpha(0.6f); // 0.0 = trong suốt, 1.0 = không trong suốt

        // Cách 2: Animation mượt mà (ObjectAnimator)
        ObjectAnimator animator = ObjectAnimator.ofFloat(txtView, "alpha", 1f, 0.6f);
        animator.setDuration(2000); // 2 giây

        btnAlpha.setOnClickListener(v -> animator.start());
    }
}

📝 Các cách thiết lập Alpha

CáchCodeĐặc điểm
Trực tiếpview.setAlpha(0.5f)Tức thì, không animation
XML Layoutandroid:alpha="0.5"Tĩnh, áp dụng lúc inflate
ObjectAnimatorObjectAnimator.ofFloat(view, "alpha", 1f, 0.3f)Mượt, có thể lặp, reverse
ViewPropertyAnimatorview.animate().alpha(0.5f).setDuration(300).start()API ngắn gọn, fluent

⚠️ Lưu ý

  • alpha ảnh hưởng cả View và **tất cả con cháu**
  • Giá trị: 0.0f (hoàn toàn trong suốt) → 1.0f (đầy đủ)
  • Khác với background alpha: view.getBackground().setAlpha(128) (0-255) chỉ làm mờ nền

Bước 4: Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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">
            <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. Nhấn nút để TextView mờ dần từ 1.0 → 0.6 trong 2 giây.