================================================
DB없이 간편저장
implementation 'androidx.preference:preference:1.1.0'
선언
var pref = androidx.preference.PreferenceManager.getDefaultSharedPreferences(this)
저장
pref.edit().putBoolean("CHECK",alarm_cb.isChecked).apply()
저장된값 불러오기
bool = pref.getBoolean("CHECK",false)
================================================
Glide사용
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
예)
Glide.with(holder.containerView).load(items.get(position).main_img).override(300,400).into(holder.containerView.pimageView)
============================
var : 처음 초기화 해도 계속 변경이 가능한 수
val : 처음 초기화하면 변경이 불가한 수
============================
jsoup 사용하기
implementation 'org.jsoup:jsoup:1.12.1'
============================
코틀린 anko 사용하기
build.gradle 모듈:앱
implementation "org.jetbrains.anko:anko:$anko_version"
추가
예)
dependencies {
implementation "org.jetbrains.anko:anko:$anko_version"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
build.gradle 프로젝트:앱명
ext.anko_version='0.10.8'
추가
예)
uildscript {
ext.kotlin_version = '1.3.31'
ext.anko_version='0.10.8'
repositories {
==================================================
ZXing library 사용하기(바코드)
implementation 'me.dm7.barcodescanner:zxing:1.9.8'
**************************************************************
문자를 QR코드로 변환
implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
예)
var bitmap: Bitmap? = null
val encoder = BarcodeEncoder()
var qrCode = QRCodeWriter()
var btm = qrCode.encode("테스트",BarcodeFormat.QR_CODE,350,350)
bitmap = encoder.createBitmap(btm);
imageView.setImageBitmap(bitmap)
=================================================
Realm 데이터 베이스 사용할려면
build.gradle 프로젝트 열고
classpath "io.realm:realm-gradle-plugin:5.2.0"
예)
dependencies {
classpath "io.realm:realm-gradle-plugin:5.2.0"
}
build.gradle 모듈 열고
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
===========================
코틀린 예제
===========================
forEach 문
var list = listOf(1,2,3,4,5,6)
list.forEach{ println(it)}
( 필터링 기능 짝수만 출력 list.filter{ it % 2 == 0}.forEach{println(it)} )
결과
1
2
3
4
5
6
=============================
for 문
// 1~3까지 출력
for ( i in 1..3){
println(i)
}
// 0~10까지 2씩 증가하며 출력
for ( i in 0..10 step 2) {
println(i)
}
// 10부터 0까지 2씩 감소하며 출력
for ( i in 10 downTo 0 step 2){
println(i)
}
=============================
list
val foods = listOf("라면","갈비","밥")
리스트를 변경 할 수 없음 listOf
val foods = mutableListOf("라면","갈비","밥")
리스트를 변경 할 수 있음 mutableListOf
foods.add("초밥") // 초밥을 맨 뒤에 추가
foods.removeAt(0) // 맨 앞의 아이템 삭제
foods[1] = "부대찌개" // foods.set(1, "부대찌개") (1번째 아이템을 부대찌개로 변경)
결과
println(foods) // 갈비,부대찌개,초밥
println(foods[0]) // 갈비
=====================================
map
val map = mapOf("a" to 1, "b" to 2,"c" to 3)
println(map["b"]) // 결과 2
변경 불가 읽기 전용맵 mapOf
val citiesMap = mutableMapOf("한국" to "서울" , "일본" to "동경" , "중국" to "북경")
//요소에 덮어 쓰기
citiesMap["한국"] = "서울틀별시"
//추가
citiesMap["미국"] = "워싱턴"
println(citiesMap["미국"]) // 결과 워싱턴
println(citiesMap["워싱턴"]) //결과 null << 맞바꿔서 해보니 값없음 나옴
변경가능맵 mutableMapOf
//맵의 키와 값을 탐색
for((k,v) in map) {
println("$k -> $v")
}
결과(변경 가능 맵 소스로 조회함)
한국 -> 서울틀별시
일본 -> 동경
중국 -> 북경
미국 -> 워싱턴
=================================
확장 함수
예) 인트 기능을 확장
fun main(){
fun Int.isEven() = this % 2 == 0
val a = 5
val b = 6
println(a.isEven()) // false
println(b.isEven()) // true
}
예2) 스트링 기능을 확장
fun main(){
fun String.test() = this + " 하이"
var hi = "hi"
println(hi.test()) // hi 하이
}
=======================
형 변환
val a = 10L
val b = 20
val c = a.toInt() // Long을 Int로
val d = b.toDouble() // Int를 Double로
val e = a.toString() // Long을 String으로
문자형을 숫자형으로
val intStr = "10"
val str = Integer.parseInt(intStr)
===========================
안드로이드 4.4 버전 벡터이미지를 사용할려면 (번들.그레이드 모듈 앱 삽입)
defaultConfig{
vectorDrawable.useSupportLibrary = true
}
===========================
오류날떄
1. 안드로이드 스튜디오를 껏다 킨다 그래도 안되면
2. 빌드 -> 클린프로젝트 그대로 안되면
3. 파일 -> Invalidate Caches / Restart
============================
안전한 호출
코틀린은 기본적으로 null을 허용하지 않음
val a : String? = null
뒤에 물음표를 붙이면 null 입력이 가능
============================
이미지(그림) 변경
playFab.setImageResource(R.drawable.ic_pause_black_24dp)
============================
늦은 초기화
lateinit var test : Int
(lateinit)
var 변수에서만 사용가능
null값으로 초기화할 수 없음
초기화 전에는 변수를 사용할 수 없음
Int,Long,Double,Float에서는 사용할 수 없음
val인데 초기화 나중에 할수 있는 lazy 도 있음
val str : String by lazy
============================
안전한 호출
val str: String? = null
물음표를 붙여서 null을 넣을 수 있는데
str?. <<요롷게 사용하면 널이 아닌 경우만 작동
//엘비스 연산자 ?:
null값이 나오면 디폴트 값을 줄수 있음
var upperCase = if(str != null) str else null //null
upperCase = str?.toUpperCase ?: "초기화 하시오" // 원래 널일떄 upperCase에 널값이 들어가고 널값이 아니면 str?.toUpperCase 이 부분이 실행이 되나 엘비스 연산
// 자를 적용하면 초기화 하시오를 널값 대신 넣을 수 있음
============================
'코틀린' 카테고리의 다른 글
안드로이드 코틀린 보이기 숨기기 (0) | 2021.05.18 |
---|---|
안드로이드 코틀린 화면 고정 (0) | 2021.05.18 |
안드로이드 코틀린 테두리 만들기(레이아웃 버튼 등등 다 됨) (0) | 2021.05.18 |
코틀린 문자가 포함되어 있는지 확인 (0) | 2021.05.18 |
코틀린 캘린터뷰(calendarView) 날자 터치시 표시 (0) | 2019.05.06 |