YSHUSH

버튼(Button) 클릭시 시간출력 이벤트 만들기 본문

Coding/Android(kotlin)

버튼(Button) 클릭시 시간출력 이벤트 만들기

코딩; 2022. 2. 8. 04:25
버튼을 클릭했을 때 이벤트 만들기

 

1. activity_main 버튼 생성

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <Button
            android:text="버튼 one"
            android:layout_width="152dp"
            android:layout_height="69dp"
            android:id="@+id/btn"
            android:onClick="onClick"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"/>
    <Button
            android:text="time 버튼"
            android:layout_width="313dp"
            android:layout_height="70dp"
            android:id="@+id/btn2"
            app:layout_constraintTop_toBottomOf="@+id/btn"
            android:layout_marginTop="32dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.501"
    />
</androidx.constraintlayout.widget.ConstraintLayout>

 

2. MainActivity.kt

버튼 클릭시 현재 시간출력 이벤트 발생

class MainActivity : AppCompatActivity(), View.OnClickListener {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

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

        val btn2 = findViewById<Button>(R.id.btn2)
        btn2.setOnClickListener {
            Toast.makeText(this.applicationContext, "버튼2 클릭!", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onClick(view: View?) {
        when(view?.id){
            R.id.btn->{
                Log.d("버튼", "클릭")

                var btn2 = findViewById<Button>(R.id.btn2)
                btn2.text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(Date())  // kk -> 0 ~ 23, hh -> 0 ~ 12
            }
        }
    }
}

'버튼 ONE'을 클릭하면 시간 출력 이벤트가 발생한다.

 

 

'Coding > Android(kotlin)' 카테고리의 다른 글

Context menu  (0) 2022.02.08
체크박스  (0) 2022.02.08
라디오 버튼  (0) 2022.02.08
버튼(Button) 클릭시 alert dialog띄우기  (0) 2022.02.08
액션 바(Action Bar)  (0) 2022.02.07