android studio ver. 3.1.4
kotlin_version = 1.2.60
switchCompat 예제입니다.
아래와 같은 이미지를 구성하기 위해서 우선 xml 을 작성하였습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?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 문을 자바 스타일로 작성하였더니 에러는 아니지만, 노란줄이 생겼어요
그래서 아래 이미지처럼 바꿔 주었어요
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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"*/ } } } } |
결과 화면
'Android Kotlin' 카테고리의 다른 글
Android Kotlin - is 와 as (1) | 2018.08.22 |
---|---|
Android Kotlin - AlertDialog example (0) | 2018.08.17 |
Android Kotlin - static method (0) | 2018.07.27 |
Android Kotlin - Variable declaration 변수 정의 (0) | 2018.07.25 |
Android Kotlin - list, for 예제 (0) | 2018.07.23 |