본문 바로가기
Android

[Android] onBackPressed와 Alert Dialog(알림창)

by eyoo 2022. 7. 12.

뒤로가기 버튼을 눌렀을때 실행되는 기능을 넣어보자.

 

먼저 컨트롤과 영문 'O' 버튼을 동시에 누르거나 generate 하여 오버라이드를 찾고 onBackPressed를 검색하여 만든다.

 

 

 

그럼 뒤로가기 버튼을 눌렀을때 실행할 코드를 적는 공간이 자동적으로 생성된다.

 

    @Override
    public void onBackPressed() {


    }

 

 

이 안에 뒤로가기를 누르면 alert 메세지를 띄워서 종료할것인지 말것인지 물어보는 기능을 만들자.

 

AlertDialog.Builder 객체를 생성하고 메인에 연결시킨다.

 

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

 

 

 

알러트 다이얼로그는 타이틀과 메세지 그리고 긍정, 부정, 중립 버튼으로 작용한다.

 

알러트 타이틀로 앱을 종료해도 되는지 물어보도록 하자.

 

alert.setTitle("앱을 종료하시겠습니까?");

 

 

 

그리고 setPositiveButton과 setNegativeButton을 사용해서 버튼을 눌렀을때 실행되는 기능을 넣는다.

 

alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        finish();
    }
});

alert.setNegativeButton("아니요", null);

# 아니요를 눌렀을때는 아무 일도 일어나지 않도록 작성했다.

 

알러트 다이얼로그가 나오고 다른 곳을 누르면 없어지는데 setCancelable로 이를 방지할수 있다.

 

alert.setCancelable(false);

 

 

이제 show로 알러트 다이얼로그가 실행될수 있도록 한다.

 

alert.show();

 

 

잘 실행되는것을 확인할수있다.

 

 

 

더보기

 

사용된 앱:

# 알람 기능을 가진 앱

 

public class MainActivity extends AppCompatActivity {

    ImageView imgAlarm;
    TextView txtTimer;
    EditText editTime;
    Button btnCancel;
    Button btnStart;
    CountDownTimer timer;
    long millisInFuture = 60000;
    long countDownInterval = 1000;
    MediaPlayer alarmSound;

    boolean isWorking = false;

    @Override
    public void onBackPressed() {

        // 알러트 다이얼로그를 띄운다.
        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        alert.setTitle("앱을 종료하시겠습니까?");
        alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });

        alert.setNegativeButton("아니요", null);
        alert.show();

    }

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

        imgAlarm = findViewById(R.id.imgAlarm);
        txtTimer = findViewById(R.id.txtTimer);
        editTime = findViewById(R.id.editTime);
        btnCancel = findViewById(R.id.btnCancel);
        btnStart = findViewById(R.id.btnStart);
        alarmSound = MediaPlayer.create(MainActivity.this,R.raw.alarm_sound);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 에디트텍스트에서 초정보를 가져온다.
                String timeStr = editTime.getText().toString().trim();

                if (timeStr.isEmpty()|| !isNumeric(timeStr) ) {
                    return;
                }

                millisInFuture = Long.valueOf(timeStr).longValue() * 1000;

                timer = new CountDownTimer(millisInFuture, countDownInterval) {
                    @Override
                    public void onTick(long l) {
                        long remain = l / 1000;
                        txtTimer.setText(remain + "초");
                        isWorking = true;
                    }

                    @Override
                    public void onFinish() {
                        txtTimer.setText("타이머가 종료되었습니다.");
                        YoYo.with(Techniques.Shake).duration(400).repeat(5).playOn(imgAlarm);
                        alarmSound.start();
                        isWorking = false;
                    }

                };
                if (isWorking == false) {
                    timer.start();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timer.cancel();
                txtTimer.setText("타이머가 취소되었습니다.");
                isWorking = false;
            }
        });




    }
    public static boolean isNumeric(String strNum) {
        if (strNum == null) {
            return false;
        }
        try {
            double d = Double.parseDouble(strNum);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}

 

 

 

 

 

 

 

댓글