왕현성
코딩발자취
왕현성
전체 방문자
오늘
어제
  • 코딩 (277)
    • Python (71)
    • Java (16)
    • MySQL (34)
    • 인공지능 (48)
      • 머신러닝 (16)
      • 딥러닝 (32)
    • 영상처리 (4)
    • Rest API (21)
    • Android Studio (25)
    • streamlit (13)
    • DevOps (22)
      • AWS (9)
      • PuTTY (5)
      • Git (4)
      • Serverless (2)
      • Docker (2)
    • IT 기술 용어 (6)
    • 디버깅 ( 오류 해결 과정 ) (17)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 영상처리역사
  • imageprocessing
  • maskimage
  • 비지도학습
  • get_long_description
  • TensorFlow
  • labelme UnocodeDecodeError
  • unsupervised
  • alibidetect
  • 딥러닝
  • pytorch
  • 영상처리
  • UnboundLocalError
  • numpy
  • yolov8
  • 의료이미징
  • 컴퓨터비전
  • tune()
  • PYTHON
  • labelme
  • PIL
  • ckpt_file
  • 영상기술
  • encoding='utf-8'
  • alibi-detection
  • pip install labelme
  • 기상탐사
  • ComputerVision
  • OpenCV
  • matplotlib

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
왕현성

코딩발자취

Android - AlertDialog 사용법
Android Studio

Android - AlertDialog 사용법

2023. 1. 27. 13:11
728x90

다이얼로그란?

 

다이얼로그는 화면에 보여지는 작은 윈도우 입니다. 화면을 채우지 않고 사용자에게 어떤 정보를 전달하거나 추가적인 정보를 입력받을 수 있습니다. 안드로이드 에서는 Dialog Class 가 있지만 이는 Base Class이므로 직접 사용하기 보다는 Sub Class인 AlertDialog 사용을 권장합니다. (Dialog class의 Sub Class로는 DatePickerDiaog, TimePickerDialog 등이 있습니다.)

 

그럼 다이얼로그 생성에 관해 이미지와 코드 위주로 설명하겠습니다.

 

1. 제목과 설명 넣기

builder.setTitle("퀴즈 끝");
        builder.setMessage("맞춘 문제는 "+count+"개 입니다. 확인을 누르시면 퀴즈가 다시 시작됩니다.");

2. 버튼 추가하기

버튼은 Positive, Negative, Neutral 3가지를 추가할 수 있습니다.

 builder.setNegativeButton("종료", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 액티비티 종료!!!
                finish();
            }
        });
//                    builder.setNeutralButton("중립",null);
        builder.setPositiveButton("확인", new DialogInterface.OnClickListener()

3. 다이얼로그의 외곽부분을 눌렀을 때 사라지지 않도록 하는 코드

// 이 다이얼로그의 외곽부분을 눌렀을 때, 사라지지 않도록 하는 코드
        builder.setCancelable(false);

4. 액티비티 종료하는 코드

finish();

 

 

퀴즈 풀이 APP 전체 코드

MainActivity.java

package com.hyunsungkr.quizapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hyunsungkr.quizapp.model.Quiz;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    // 화면의 뷰 연결용 멤버 변수
    TextView txtQuiz;
    ProgressBar progressBar;
    TextView txtResult;
    Button btnTrue;
    Button btnFalse;

    // 현재 퀴즈의 인덱스 값!
    int currentQuizIndex = 0;

    // 데이터 저장용 멤버 변수
    ArrayList<Quiz> quizArrayList = new ArrayList<>();
    int count = 0;

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

        // 1. 화면의 뷰 연결
        txtQuiz = findViewById(R.id.txtQuiz);
        txtResult = findViewById(R.id.txtResult);
        progressBar = findViewById(R.id.progressBar);
        btnTrue = findViewById(R.id.btnTrue);
        btnFalse = findViewById(R.id.btnFalse);

        // 2. 퀴즈를 만든다! => 퀴즈 클래스를 메모리에 만들어준다.
        //    => 클래스를 가지고 객체생성 해준다.
        //      퀴즈가 10개이니 객체를 10개 만들어준다.

        setQuiz();

        // 3. 문제를 출제한다. ( 화면에 )
        Quiz q = quizArrayList.get(currentQuizIndex);

        txtQuiz.setText(q.question);

        // 4. ProgressBar를 표시하자.
        progressBar.setProgress(currentQuizIndex+1);


        // 5. 참 / 거짓 버튼에 대한 처리
        btnTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1. 현재 문제의 정답을 가져온다.
                Quiz q = quizArrayList.get(currentQuizIndex);

                // 2. 이 버튼이 트루버튼이므로
                // 정답이 트루이면
                // 결과에 "정답입니다"라고 표시
                // 그렇지 않으면 "틀렸습니다."
                if(q.answer==true){
                    txtResult.setText("정답입니다.");
                    count = count +1;
                }else{
                    txtResult.setText("틀렸습니다.");
                }
                // 3. 다음 문제를 출제한다.
                if(currentQuizIndex==9){

                    showAlertDialog();

                    return;
                }else {


                    currentQuizIndex = currentQuizIndex + 1;

                    q = quizArrayList.get(currentQuizIndex);
                    txtQuiz.setText(q.question);

                    // 4. 프로그레스바도 하나 증가
                    progressBar.setProgress(currentQuizIndex + 1);
                }
            }
        });
        btnFalse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1. 현재 문제의 정답을 가져온다.
                Quiz q = quizArrayList.get(currentQuizIndex);

                // 2. 이 버튼이 펄스버튼이므로
                // 정답이 폴스이면
                // 결과에 "정답입니다"라고 표시
                // 그렇지 않으면 "틀렸습니다."
                if(q.answer==false){
                    txtResult.setText("정답입니다.");
                    count = count +1;
                }else{
                    txtResult.setText("틀렸습니다.");
                }
                // 3. 다음 문제를 출제한다.
                if(currentQuizIndex==quizArrayList.size()-1){
                    showAlertDialog();
                    return;


                }else {


                    currentQuizIndex = currentQuizIndex + 1;

                    q = quizArrayList.get(currentQuizIndex);
                    txtQuiz.setText(q.question);

                    // 4. 프로그레스바도 하나 증가
                    progressBar.setProgress(currentQuizIndex + 1);
                }
            }
        });


    }

    private void showAlertDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        // 이 다이얼로그의 외곽부분을 눌렀을 때, 사라지지 않도록 하는 코드
        builder.setCancelable(false);
        builder.setTitle("퀴즈 끝");
        builder.setMessage("맞춘 문제는 "+count+"개 입니다. 확인을 누르시면 퀴즈가 다시 시작됩니다.");
        builder.setNegativeButton("종료", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 액티비티 종료!!!
                finish();
            }
        });
//                    builder.setNeutralButton("중립",null);
        builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 확인 버튼을 눌렀을 때 실행할 코드 작성.

                // 1. 첫번째 문제가 다시 화면에 나와야한다.
                currentQuizIndex=0;
                Quiz q=quizArrayList.get(0);
                txtQuiz.setText(q.question);

                //2. 프로그레스바도 처음부터 나와야한다.
                progressBar.setProgress(currentQuizIndex+1);

                //3. 정답 갯수는 0으로 만들어야한다.
                count = 0;

            }
        });
        builder.show();

    }

    private void setQuiz() {
        Quiz q= new Quiz( R.string.q1,true );
        quizArrayList.add(q);

        q = new Quiz(R.string.q2,false);
        quizArrayList.add(q);

        q = new Quiz(R.string.q3,true);
        quizArrayList.add(q);

        q = new Quiz(R.string.q4,false);
        quizArrayList.add(q);

        q = new Quiz(R.string.q5,true);
        quizArrayList.add(q);

        q = new Quiz(R.string.q6,false);
        quizArrayList.add(q);

        q = new Quiz(R.string.q7,true);
        quizArrayList.add(q);

        q = new Quiz(R.string.q8,false);
        quizArrayList.add(q);

        q = new Quiz(R.string.q9,true);
        quizArrayList.add(q);

        q = new Quiz(R.string.q10,false);
        quizArrayList.add(q);

    }
}

확인을 클릭 시 처음 화면으로 돌아가고 종료를 누를 시 APP이 종료되도록 구현 완료.

'Android Studio' 카테고리의 다른 글

Android - Activity 간의 데이터 전달 방법 (단방향/양방향) / Back(뒤로가기) 이벤트 처리 방법  (0) 2023.01.30
Android - Activity Life Cycle 주요 함수와 화면 전환 방법  (0) 2023.01.30
Android - CountDownTimer  (0) 2023.01.27
Android - TextView의 setText함수에 숫자를 쉽게 넣어주는 방법 / todo  (0) 2023.01.26
Android - EditText사용법과 문자열 가져오는 방법 / 로그처리하는 방법 / Toast , Snackbar 메시지 처리방법  (0) 2023.01.26
    'Android Studio' 카테고리의 다른 글
    • Android - Activity Life Cycle 주요 함수와 화면 전환 방법
    • Android - CountDownTimer
    • Android - TextView의 setText함수에 숫자를 쉽게 넣어주는 방법 / todo
    • Android - EditText사용법과 문자열 가져오는 방법 / 로그처리하는 방법 / Toast , Snackbar 메시지 처리방법
    왕현성
    왕현성
    AI 머신비전 학습일지

    티스토리툴바