Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 뷰(View) 불투명도(Opacity) 설정하는 방법 완벽 가이드

Android에서 뷰(View) 불투명도 설정하기

이 예제는 Android 앱에서 뷰(View)의 불투명도(opacity)를 설정하는 방법을 단계별로 보여줍니다. ObjectAnimator를 활용하면 버튼 클릭 한 번으로 뷰가 서서히 투명해지는 부드러운 알파 애니메이션 효과를 손쉽게 구현할 수 있습니다.

1단계 − Android Studio에서 새 프로젝트 생성

Android Studio를 실행한 뒤 File ⇒ New Project 메뉴로 이동하여 새 프로젝트를 만들고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 − res/layout/activity_main.xml 코드 작성

레이아웃 파일에 파란색 배경의 TextView와 불투명도 변경을 트리거할 Button을 추가합니다.

<?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="fill_parent"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="86dp"
        android:background="#011ffd"
        android:gravity="center"
        android:text="TextView"
        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="Click here to set view Alpha/Opacity of in android programmatically" />
</RelativeLayout>

3단계 − src/MainActivity.java 코드 작성

메인 액티비티에서 ObjectAnimator 객체를 생성하고, 버튼 클릭 시 4초 동안 뷰의 불투명도가 서서히 변하도록 애니메이션을 시작합니다.

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView txt;
    Button btn;
    ObjectAnimator objectanimator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView)findViewById(R.id.textView1);
        btn = (Button)findViewById(R.id.button1);
        objectanimator = ObjectAnimator.ofFloat(txt,"Opacity",0.6f);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                objectanimator.setDuration(4000);
                objectanimator.start();
            }
        });
    }
}

4단계 − Manifests/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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 Android에서 뷰(View) 불투명도(Opacity) 설정하는 방법 완벽 가이드 실행 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 다음과 같은 기본 화면이 표시됩니다.

Android에서 뷰(View) 불투명도(Opacity) 설정하는 방법 완벽 가이드

추가 팁: 간단한 방법

애니메이션 없이 즉시 불투명도를 변경하고 싶다면 setAlpha() 메서드를 사용하는 것이 더 간단합니다. 예를 들어 txt.setAlpha(0.6f)처럼 호출하면 해당 뷰가 즉시 60% 불투명도로 변경됩니다. 값의 범위는 0.0(완전 투명)부터 1.0(완전 불투명)까지이며, 점진적인 전환 효과가 필요할 때는 위 예제처럼 ObjectAnimator를 활용하는 것이 좋습니다.