코딩 일기장/Android(Kotlin)

[안드로이드] 4장 연습문제 7번

minWachya 2021. 3. 20. 17:59
반응형

7번 :

체크 박스를 선택할 때마다 버튼의 속성이 설정되도록 프로젝트를 작성하시오.

 

실행 결과

45도 회전 버튼은... 한 번만 회전하게 했다. 다시 클릭하면 원상태가 됨.

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enable 속성"
android:id="@+id/cbEnable" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clickable 속성"
android:id="@+id/cbClickable" />
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="45도 회정"
android:id="@+id/cbRotation" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/btn"
android:layout_marginTop="100dp"/>
</LinearLayout>

 

MainActivity.kt

package com.example.mytest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import kotlin.system.exitProcess
class MainActivity : AppCompatActivity() {
// 변수 선언
lateinit var cbEnabel : CheckBox
lateinit var cbClickable : CheckBox
lateinit var cbRotation : CheckBox
lateinit var btn : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "연습문제 4-7"
// 코틀린과 변수 연결
cbEnabel = findViewById<CheckBox>(R.id.cbEnable)
cbClickable = findViewById<CheckBox>(R.id.cbClickable)
cbRotation = findViewById<CheckBox>(R.id.cbRotation)
btn = findViewById<Button>(R.id.btn)
// cbEnabel 버튼 클릭 시 Enabel 설정 변경
cbEnabel.setOnClickListener {
if (cbEnabel.isChecked) btn.setEnabled(false)
else btn.setEnabled(true)
}
// cbClickable 버튼 클릭 시 Clickable 설정 변경
cbClickable.setOnClickListener {
if (cbClickable.isChecked) btn.setClickable(false)
else btn.setClickable(true)
}
// cbRotation 버튼 클릭 시 45도 회전
cbRotation.setOnClickListener {
if (cbRotation.isChecked) btn.setRotation(45.0f)
else btn.setRotation(-0.0f)
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

버튼 회전하는 거... 실수형으로 안 써줘서 시간 잡아먹은 아주 간단했던 문제!^^

 

느낀 점:아... 강종만 안 되어도아주 잘 만든 앱이구나...

반응형