android studio ver. 3.1.4
kotlin_version = 1.2.60



switchCompat 예제입니다.

아래와 같은 이미지를 구성하기 위해서 우선 xml 을 작성하였습니다.


 


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lay_push"
        android:padding="20dp"
        android:foreground="?android:attr/selectableItemBackground">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="start|center_vertical"
            android:text="알림설정" />

        <android.support.v7.widget.SwitchCompat
            android:id="@+id/sc_push"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|center_vertical"
            android:checked="true"/>

    </FrameLayout>
</android.support.constraint.ConstraintLayout>


java 코드 작성

초기화는 open 으로 작성하였습니다.
아직 코틀린 문법이 if 문을 자바 스타일로 작성하였더니 에러는 아니지만, 노란줄이 생겼어요
그래서 아래 이미지처럼 바꿔 주었어요



아래와 같이 클릭으로 토글하는 간단한 예제를 작성하여 보았습니다. 
Framelayout 을 클릭시에는 performClick 으로 토글시켜보았습니다. 
이렇게 작성을 해보니, setOnCheckedChangeListener 안에서는 워닝 메시지가 나옵니다. "RenameTo _" 
 scPush.setOnCheckedChangeListener { buttonView, isChecked -> }
 이것을 
scPush.setOnCheckedChangeListener { _, isChecked -> } 이렇게 변경을 했어요.
class SplashActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var scPush: SwitchCompat    // lateinit 지연초기화
    private var init: String = "N"

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

        // lay 클릭시 토글
        val lay: FrameLayout = findViewById(R.id.lay_push)
        lay.setOnClickListener(this)

        // 스위치 버튼
        scPush = findViewById(R.id.sc_push)
        scPush.isChecked = init == "Y"

        scPush.setOnCheckedChangeListener { buttonView, isChecked ->
            i("scPush isChecked , ", isChecked)
            init = if (isChecked) { // on
                "Y"
            } else {    // off
                "N"
            }
            i("scPush init , ", init)
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.lay_push -> {
                d("lay_push onClick , ", init)
                scPush.performClick()
                /*init = if(init == "Y") {
                    "N"
                } else {
                    "Y"
                }
                scPush.isChecked = init == "Y"*/
            }
        }
    }
}

결과 화면


+ Recent posts