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

안드로이드 스낵바(Snackbar) 통합 방법 – 단계별 완벽 가이드

스낵바(Snackbar)는 안드로이드의 토스트(Toast)와 비슷하지만, 사용자가 탭할 수 있는 액션 버튼을 함께 제공할 수 있다는 점이 다릅니다. 스낵바는 화면 하단에 메시지를 표시하며, 다른 뷰와의 상호작용 없이 자동으로 나타났다가 일정 시간이 지나면 저절로 사라집니다.

이 글에서는 안드로이드 앱에 스낵바를 통합하는 전체 과정을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project를 선택한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계: 디자인 서포트 라이브러리 의존성 추가

build.gradle 파일을 열고 아래와 같이 디자인 서포트 라이브러리(design support library) 의존성을 추가합니다.

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.myapplication"
      minSdkVersion 19
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support:design:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

3단계: 레이아웃 파일 작성

res/layout/activity_main.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:id="@+id/layout"
   android:layout_height="match_parent">
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:text="Click here" />
</android.support.design.widget.CoordinatorLayout>

위 코드에서 레이아웃 ID를 선언한 이유는 스낵바가 반드시 부모 뷰(parent view)를 필요로 하기 때문입니다. 사용자가 버튼을 클릭하면 화면 하단에 스낵바가 나타납니다.

4단계: MainActivity 코드 작성

src/MainActivity.java에 다음 코드를 추가합니다.

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   CoordinatorLayout coordinatorLayout;
   @TargetApi(Build.VERSION_CODES.O)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      coordinatorLayout=findViewById(R.id.layout);
      Button button=findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Snackbar snackbar = Snackbar
            .make(coordinatorLayout, "Welcome to tutorialspoint.com", Snackbar.LENGTH_LONG)
            .setAction("Click", new View.OnClickListener() {
               @Override
               public void onClick(View view) {
                  String url = "https://www.tutorialspoint.com";
                  Intent i = new Intent(Intent.ACTION_VIEW);
                  i.setData(Uri.parse(url));
                  startActivity(i);
               }
            });
            // Changing message text color
            snackbar.setActionTextColor(Color.RED);
            // Changing action button text color
            View sbView = snackbar.getView();
            TextView textView = (TextView) sbView.findViewById(
            android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
         }
      });
   }
}

핵심 로직만 추려 보면 다음과 같습니다. 사용자가 버튼을 클릭하면 아래 코드에 따라 스낵바가 화면에 표시됩니다.

Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Welcome to tutorialspoint.com", Snackbar.LENGTH_LONG)
.setAction("Click", new View.OnClickListener() {
   @Override
   public void onClick(View view) {
      String url = "https://www.tutorialspoint.com";
      Intent i = new Intent(Intent.ACTION_VIEW);
      i.setData(Uri.parse(url));
      startActivity(i);
   }
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();

위 코드에서는 "Welcome to tutorialspoint.com"이라는 메시지와 함께 "Click"이라는 액션 버튼이 있는 스낵바를 선언했습니다. 사용자가 Click 버튼을 누르면 기본 브라우저를 통해 tutorialspoint 웹사이트가 열립니다. 또한 setActionTextColor()로 액션 버튼의 텍스트 색상을 빨간색으로, 메시지 텍스트 색상은 노란색으로 각각 변경했습니다.

5단계: 매니페스트 파일 수정

manifest.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="com.example.andy.myapplication">
   <uses-permission android:name="android.permission.INTERNET" />
   <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.permission.INTERNET)을 선언했습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 기기 목록에서 본인의 모바일 기기를 선택하면, 아래와 같은 기본 화면이 기기에 표시됩니다.

안드로이드 스낵바(Snackbar) 통합 방법 – 단계별 완벽 가이드

버튼을 클릭하면 위 이미지처럼 Click 버튼이 포함된 스낵바 메시지가 화면 하단에 나타납니다.

안드로이드 스낵바(Snackbar) 통합 방법 – 단계별 완벽 가이드

스낵바의 "Click" 버튼을 누르면 기본 브라우저가 열리고 tutorialspoint.com 웹사이트로 이동합니다.