Android

Android Studio QuizApp, progressBar, Alert, strings.xml 다국어 처리, 반복되는 작업은 유지보수를 위해 메소드로 만들기, 객체들을 담은 리스트의 활용, IndexOutOfBounds를 방지하기,

leopard4 2023. 1. 27. 13:20

0
완성된 퀴즈앱

 

text : @string/txtQuiz

@string/txtQuiz (매핑변수 strings.xml 과 연결, 다국어 처리를 위한 소프트코딩)

다국어처리를 위해 언어적 요소는 strings.xml 파일에 모은다

이 파일을 번역본으로 여러개 만들어놓으면 다국어 처리가 가능하다. (업체에 맡길수도 있다)

디폴트 언어를 영어로 설정가능 예시) strings_en.xml (자세한 사항은 메뉴얼을 참조)

weight 설정 일괄처리( 요지는 component Tree 부분에서 이런것도 가능하다는것)

 

 

Main 전체 코드

package com.leopard4.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 com.google.android.material.snackbar.Snackbar;
import com.leopard4.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; // 현재 퀴즈의 인덱스
    int correctAnswerCount = 0; // 정답 개수

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 0. 레이아웃을 화면에 보여준다.




        // 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.setProgress(currentQuizIndex + 1);
        // 5. 참 / 거짓 버튼에 대한 처리
        btnTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 퀴즈가 다 되면, 토스트나 스낵바로
                // 유저한테, "퀴즈가 끝났습니다." 라고 알려준다.
                if (currentQuizIndex >= quizArrayList.size() - 1) {

                    showAlertDialog();

                    return ;
                }
                // 5-1. 현재 질문의 정답을 가져온다.
                Quiz q = quizArrayList.get(currentQuizIndex);

                // 5-2 이 버튼이 트루 버튼이므로
                // 정답이 트루이면
                // 결과에 "정답입니다" 라고 표시
                // 그렇지 않으면 " 틀렸습니다."로 표시

                if (q.answer == true) {
                    txtResult.setText("정답입니다.");
                    correctAnswerCount = correctAnswerCount + 1;
                } else {
                    txtResult.setText("틀렸습니다.");
                }

                // 5-3 다음 문제를 출제한다.


                currentQuizIndex = currentQuizIndex + 1;

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

                // 5-4 프로그래스바를 증가시킨다.
                progressBar.setProgress(currentQuizIndex + 1);

            }
        });

        btnFalse.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (currentQuizIndex >= quizArrayList.size() - 1) {

                    showAlertDialog();

                    return ;
                }

                // 5-1. 현재 질문의 정답을 가져온다.
                Quiz q = quizArrayList.get(currentQuizIndex);

                // 5-2 이 버튼이 false 버튼이므로
                // 정답이 false이면
                // 결과에 "정답입니다" 라고 표시
                // 그렇지 않으면 " 틀렸습니다."로 표시

                if (q.answer == false) {
                    txtResult.setText("정답입니다.");
                    correctAnswerCount = correctAnswerCount + 1;
                } else {
                    txtResult.setText("틀렸습니다.");
                }

                // 5-3 다음 문제를 출제한다.
                currentQuizIndex = currentQuizIndex + 1;


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

                // 5-4 프로그래스바를 증가시킨다.
                progressBar.setProgress(currentQuizIndex + 1);
            }

        });


    }

    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        // 이 다이얼로그의 외곽부분을 눌렀을때, 사라지지 않도록 하는 코드
        builder.setCancelable(false);
        builder.setTitle("Game Over");
        builder.setMessage("맞춘문제는 : " + correctAnswerCount + "개 입니다. 확인을 누르시면 퀴즈가 다시 시작됩니다.");
//                    builder.setNeutralButton("중립", null);
        // 종료 버튼을 눌렀을때, 앱을 종료시키는 코드
        builder.setNegativeButton("종료", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish(); // AppCompatActivity 에서 제공하는 종료 메소드
            }
        });
        builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 확인버튼 눌렀을때 실행 코드 작성!
                // 퀴즈를 다시 시작한다.
                // 문제, 프로그래스바, 정답갯수 초기화
                currentQuizIndex = 0;
                correctAnswerCount = 0;
                Quiz q = quizArrayList.get(currentQuizIndex);
                txtQuiz.setText(q.question);
                txtResult.setText("");
                progressBar.setProgress(currentQuizIndex + 1);
            }
        });
        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);
    }

}