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

안드로이드에서 싱글톤(Singleton) 패턴으로 알럿 다이얼로그 구현하는 방법

예제를 시작하기에 앞서, 싱글톤(singleton) 디자인 패턴이 무엇인지 먼저 알아보겠습니다. 싱글톤은 하나의 클래스에 대해 인스턴스 생성을 단 하나로 제한하는 디자인 패턴입니다. 대표적인 활용 사례로는 동시성(concurrency) 제어와, 애플리케이션 전체가 데이터 저장소에 접근할 수 있도록 하는 중앙 집중식 접근 지점의 생성 등이 있습니다.

이번 예제는 안드로이드에서 싱글톤 클래스를 활용해 알럿 다이얼로그(AlertDialog)를 표시하는 방법을 보여줍니다.

1단계: 새 프로젝트 생성

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

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity"
    android:orientation = "vertical">
    <Button
        android:id = "@+id/show"
        android:text = "Alert Dialog from singleTone"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 코드에는 버튼이 하나 포함되어 있습니다. 사용자가 이 버튼을 클릭하면 싱글톤 클래스에서 알럿 다이얼로그가 표시됩니다.

3단계: 메인 액티비티 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    Button show;
    singleTonExample singletonexample;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = findViewById(R.id.show);
        singletonexample = singleTonExample.getInstance();
        singletonexample.init(getApplicationContext());
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                singletonexample.AlertDialog(MainActivity.this);
            }
        });
    }
}

4단계: 싱글톤 클래스 작성

위 코드에서는 singleTonExample을 싱글톤 클래스로 사용했습니다. 따라서 singleTonExample.java라는 이름의 클래스 파일을 생성하고 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
public class singleTonExample {
    static TextToSpeech t1;
    private static singleTonExample ourInstance = new singleTonExample();
    private Context appContext;
    private singleTonExample() { }
    public static Context get() {
        return getInstance().getContext();
    }
    public static synchronized singleTonExample getInstance() {
        return ourInstance;
    }
    public void init(Context context) {
        if (appContext == null) {
            this.appContext = context;
        }
    }
    private Context getContext() {
        return appContext;
    }
    public void AlertDialog(final MainActivity mainActivity) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mainActivity);
        alertDialogBuilder.setMessage("Are you sure, You wanted to make decision");
        alertDialogBuilder.setPositiveButton("yes",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(mainActivity, "You clicked yes button", Toast.LENGTH_LONG).show();
            }
        });
        alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mainActivity.finish();
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
}

애플리케이션 실행하기

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

안드로이드에서 싱글톤(Singleton) 패턴으로 알럿 다이얼로그 구현하는 방법

화면의 버튼을 클릭하면, 아래 그림과 같이 싱글톤 클래스에서 알럿 다이얼로그가 나타납니다.

안드로이드에서 싱글톤(Singleton) 패턴으로 알럿 다이얼로그 구현하는 방법