안드로이드 코드를 작성하다보면 view를 다룰 때 꼭 한번 context를 parameter로 요청하는 경우가 있다.
그냥 단어만 알고있던 이것에 대해서 한 번 알아보고 어떤 쓸모가 있는지 알아보고 다른 인스턴스에 접근하는 방법을 탐구해보자. ( 인스턴스 접근방법을 알고 싶다면 맨 아래 문단을 참고하기 바랍니다. )
Context의 정의
위는 Android Developers에 게시된 문서의 정의부분이다. 읽어보니 안드로이드의 시스템 요소와 자원에 접근하기 위한 추상 클래스라고 한다. 문서를 조금더 찾아보니 Activity, Application, Service의 base class로 사용된다고 한다. 이를 알고 나니 기본적인 시스템 추상클래스라는 느낌을 알겠다.
용례
어플리케이션의 resource 획득
새로운 activity 시작
view 생성
system service 획득
사용 예시에는 위와 같은 경우가 있는데 이는 getResource(), startActivity() 등의 함수를 어느정도 다루어봤다면 당연히 알 것이다. 이 정도로 끝났다면 나는 이번 포스팅을 작성하지 않았을 것이다. 생각해보니 이를 이용하면 CustomView를 만들때 해당 뷰가 속한 액티비티의 함수를 CustomView에서 자유롭게 호출할 수 있을것 같았다.
다른 액티비티에서 변수, 함수 호출
아래는 내가 만든 CustomButton이다. 우선 생성자를 호출할 때 뷰는 모든 Context를 인자로 받아야하는데 이를 MainActivity클래스로 캐스팅하여 변수로 저장했다.
그 다음 버튼을 클릭할 때 startForegroundService를 호출하도록 실험해봤는데.... 된다..... MainActivity는 싱글톤 클래스고 Context를 MainActivity으로 캐스팅해서 안 될줄 알았는데 된다....
다른 액티비티나 커스텀 뷰에서 메인 액티비티의 변수나 함수에 접근하는데 stack overflow에 서칭도 해보고 고민을 많이 했는데 너무 간단하게 된다.... 아무튼 오늘 좋은 지식을 하나 얻었다.
이번 글에서는 처음으로 코틀린을 공부해보는 만큼 코틀린에 쓰이는 기본타입(numbers, characters, booleans, arrays, and strings)에 대해서 알아보도록 하겠습니다.
1. Numbers
1. 정수
1. 파이썬, javascript처럼 변수에 따로 타입을 선언하지 않음
2. 일반적인 정수를 저장하면 Int로 설정
3. Int의 범위 밖이나 뒤에 L을 추가하면 Long으로 설정
4. 변수이름 : 타입 = ? 구문을 통해서 직접 타입 설정 가능
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
2. 실수
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
1. 일반 실수 입력시 Double로 설정
2. 뒤에 F또는 f 추가시 float으로 설정되고 범위 밖의 데이터는 소멸
3. 독립성
코틀린은 일반적인 언어처럼 숫자 파라미터가 포괄적인게 아니라 해당 파라미터만 수용가능, 그렇지 않을 경우 에러 발생
fun main() {
fun printDouble(d: Double) { print(d) }
val i = 1
val d = 1.1
val f = 1.1f
printDouble(d)
// printDouble(i) // Error: Type mismatch
// printDouble(f) // Error: Type mismatch
}
4.. 리터럴 상수(Literal constants)
10진수, Decimals:123
Longs are tagged by a capitalL:123L
8진수, Hexadecimals:0x0F
2진수, Binaries:0b00001011
NOTE: Octal literals are not supported.
Doubles by default:123.5,123.5e10
Floats are tagged byforF:123.5f
5. 가독성을 위한 언더스코어 사용가능
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
6. 변환
val b: Byte = 1 // OK, literals are checked statically
val i: Int = b // ERROR
타입은 명백히 독립적이므로 바로 대입하는것은 불가(java와 다름)
변환하기 위해선 toInt,toLong등의 메서드 사용필요
val i: Int = b.toInt() // OK: explicitly widened
print(i)
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char
*오퍼레이터 오버로딩
val l = 1L + 3 // Long + Int => Long
서로 다른 두 데이터의 수학적 계산 결과의 타입은 자동으로 최적화됨
*나눗셈으로 인한 타입 결정은 java와 같음
7.비교(Floating point numbers comparison)
The operations on floating point numbers discussed in this section are:
Equality checks:a == banda != b
Comparison operators:a < b,a > b,a <= b,a >= b
Range instantiation and range checks:a..b,x in a..b,x !in a..b
2.Characters
Characters are represented by the typeChar. They can not be treated directly as number
fun check(c: Char) {
if (c == 1) { // ERROR: incompatible types
// ...
}
}
특수문자사용 :\t,\b,\n,\r,\',\",\\and\$
유니코드 인코딩 : '\uFF00'
Convert a character to anIntnumber
fun decimalDigitValue(c: Char): Int {
if (c !in '0'..'9')
throw IllegalArgumentException("Out of range")
return c.toInt() - '0'.toInt() // Explicit conversions to numbers
}
3.Booleans
The typeBooleanrepresents booleans, and has two values:trueandfalse.
Built-in operations on booleans include
||– lazy disjunction
&&– lazy conjunction
!- negation
4.Arrays
Arrays in Kotlin are represented by theArrayclass
메서드 : set,get( that turn into[] by operator overloading conventions )
특성 : size
사용법
1. arrayOf(1, 2, 3)creates an array[1, 2, 3]
2. arrayOfNulls()library function can be used to create an array of a given size filled with null elements.
3. Arrayconstructor
it takes array size and the function that can return the initial value of each array element given its index
// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { println(it) }
Primitive type arrays
ByteArray,ShortArray,IntArray등 Kotlin에는 특수한 배열들이 있습니다. 각 배열은 Array에 상속되지 않지만 동일한 메서드를 사용하며 []를 통해 접근이 가능합니다.
// Array of int of size 5 with values [0, 0, 0, 0, 0]
val arr = IntArray(5)
// e.g. initialise the values in the array with a constant
// Array of int of size 5 with values [42, 42, 42, 42, 42]
val arr = IntArray(5) { 42 }
// e.g. initialise the values in the array using a lambda
// Array of int of size 5 with values [0, 1, 2, 3, 4] (values initialised to their index value)
var arr = IntArray(5) { it * 1 }
5.Strings
Strings are represented by the typeString
특성
1.Strings are immutable
2.Elements of a string are characters that can be accessed by the indexing operation:s[i]
3.string can be iterated over with afor-loop:
for (c in str) {
println(c)
}
4. concatenate strings using the+operator,as long as the first element in the expression is a string
val s = "abc" + 1
println(s + "def")
String literals
1.특수 문자사용
val s = "Hello, world!\n"
2. """ 사용
val text = """
for (c in "foo")
print(c)
"""
String templates
$기호를 사용해서 템플릿으로 사용할 수 있음
val i = 10
println("i = $i") // prints "i = 10"
중괄호를 사용해서 임의의 표현까지 템플릿으로 사용 가능
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"