Android Kotlin Double Click Close - 두 번 클릭하여 종료

Notepad96

·

2021. 10. 27. 00:21

300x250

 

 


1. 결 과

 

 

 


2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back Double Click Close"
        android:textSize="22sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 


3. MainActivity.kt

package com.example.dblclickclose

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    var clickTime: Long = 0
    override fun onBackPressed() {
        var current = System.currentTimeMillis()
        if(current - clickTime >= 3500) {   // 3.5 초
            clickTime = current

            Toast.makeText(applicationContext, "한번 더 클릭 시 종료됩니다", Toast.LENGTH_LONG).show()
            // Toast.LENGTH_SHORT = 2.5 초
            // Toast.LENGTH_LONG = 3.5 초
        } else {
            super.onBackPressed()
        }
    }
}

 

# clickTime 이라는 뒤로가기 버튼을 첫 번째 클릭 시 시간을 담을 변수를 선언해준다.

 

 

# 뒤로가기 버튼을 두 번째 클릭 시 현재 시간을 구하여 첫 번째 클릭하였던 시간 clickTime과 차이를 구함으로써 클릭한 간격을 구할 수 있다.

 

위 예시에서는 시간 차가 3500보다 적을 경우 종료되도록 하였으며, 단위는 ms로 3500은 3.5초이다.

 

 

# Toast 메시지를 보여줄 때 지속 시간은 다음과 같으며

 

Toast.LENGTH_LONG = 3500 = 3.5 초

Toast.LENGTH_SHORT = 2500 = 2.5 초

 

이에 맞추어 클릭 간 시간 간격을 지정하면 종료 메시지를 보여주는 동안만 종료를 하도록 할 수 있다.

 

 

 

 


4. 전체 코드

 

 

GitHub - Notepad96/BlogExample

Contribute to Notepad96/BlogExample development by creating an account on GitHub.

github.com

 

 

300x250