Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

yourginieus

setImageResources, tools, dependencies 본문

Android/Android Kotlin 기초 실습 정리

setImageResources, tools, dependencies

EOJIN 2022. 10. 25. 03:29
  • 이미지 리소스 추가
    • res/Drawable 에 이미지 리소스를 추가하면 됨
    • 앱의 모든 리소스(이미지, 아이콘, 색상, 문자열, xml 레이아웃 등)을 res 폴더에 저장하며, drawable 폴더는 앱의 모든 이미지 리소스를 저장하는 곳
    • drawable 파일 안의 .xml 파일은 아이콘을 벡터 이미지로 설명하는 xml 파일임
      • 벡터를 사용하면 다양한 크기와 해상도를 이용할 수 있음
      • PNG나 GIF같은 Bitmap 이미지는 다른 디바이스에 맞게 크기를 조정해야 할 수 있음
    • 이미지 파일을 복사해서 drawable 폴더에 붙여넣으면 됨
      • drawable24 폴더가 아닌 drawable 폴더임!
  • ImageView
    • android:src 속성을 통해 이미지 소스 리소스를 나타낼 수 있음
<ImageView
   android:id="@+id/dice_image"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"
   android:src="@drawable/dice_1" />
  • .kt 파일에서도 동적으로 이미지 변경 가능
    • setImageResource(리소스 ID) 이용하기
val diceImage: ImageView = findViewById(R.id.dice_image)

val drawableResource = when (randomInt) {
   1 -> R.drawable.dice_1
   2 -> R.drawable.dice_2
   3 -> R.drawable.dice_3
   4 -> R.drawable.dice_4
   5 -> R.drawable.dice_5
   else -> R.drawable.dice_6
}

diceImage.setImageResource(drawableResource)
  • findViewById() 조금만 사용하기
    • Android system은 매번 뷰 계층 전체를 검색하기 때문에 setOnClickListener 등의 메소드에서 findViewById를 매번 호출하면 큰 낭비임
    • findViewById를 한 번만 호출하고, 그 때 object를 field에 저장해두고 계속 사용하는 것이 좋음
    • onCreate()에서 setContentView() 를 통해 불려지기 전까지, layout 내의 view는 memory 내의 object에 전혀 access할 수 없음
      • 따라서 처음에 null로 지정해 둔 후 나중에 선언할 수도 있고
      • lateinit var를 이용할 수 있음
        • lateinit 키워드를 사용하면, 코틀린 컴파일러에서 코드가 변수를 호출하기 전에 변수가 초기화 됨을 약속 함 -> 변수를 null로 초기화 할 필요가 없음
        • 또한 non-nullable 이라고 간주할 수 있음
        • lateinit으로 위에서 선언해 둔 후, onCreate에서 setContentView 다음으로 해당 객체에 값을 넣어주면 됨
lateinit var diceImage : ImageView

.
.

diceImage = findViewById(R.id.dice_image)
  • tools : src = '이미지ID"
    • android:src 는 이미지 소스를 지정해주지만, tools:src는 미리보기에서의 이미지를 지정함
    • tools는 Android Studio의 preview 또는 design editor에서 사용되는 placeholder 내용을 정의할 때 사용 됨
    • 사용된 tools 속성은 컴파일 시 삭제됨!
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   ...
   >
   
   <ImageView
   	...
    android:src="@drawable/empty_dice" 
    tools:src="@drawable/dice_1" />

-> Preview에 이미지가 dice1로 표시 됨. 실제 앱애서는 empty dice로 남아 있음

  • API 수준 및 호환성 파악
    • Android에서 다양한 장치에 대해 완전히 다른 별개의 앱을 만드는 것이 아닌 하나를 계속 공유하기 위해서는, 알아야 할 제약사항과 호환성 전략이 있음
    • Android API 버전과 Android Jetpack 라이브러리를 사용하여 이전 장치를 지원하는 방법이 있음
    • API 레벨 확인
      • Android OS에는 과자의 이름을 알파벳 순서로 딴 버전 번호가 있음
      • 각 OS 버전에는 새로운 기능이 탑재 됨
      • 하드웨어가 무엇을 지원할 수 있는지와 업데이트 여부 등에 따라 다양한 OS 버전을 제공하는 디바이스가 존재 함
      • 앱 프로젝트를 만들 때 앱이 지원하는 최소 API 수준을 지정 함 -> 앱에서 지원하는 가장 오래된 Android 버전 지정
      • 컴파일되는 수준과 타겟팅되는 수준도 지정함 -> Gradle 빌드 파일의 구성 parameter
      • Gradle Scripts 폴더에서 build,gradle(Module:app) 열고(모듈이 하나일 때는 project 에서 해도 괜찮지만 앱이 분할되거나 할 때는 다른 모듈이 적용될 수 있기 때문에)
        • compileSdkVersion : Gradle이 앱을 컴파일할 때 사용해야 하는 Android API 수준 지정(앱이 지원하는 Android의 최신 버전)
        • targetSdkVersion : 앱을 테스트한 최신 API, compileSdk와 같은 경우가 많음
        • minSdkVersion : 이 API 수준보다 오래된 Android OS를 실행하는 장치에서는 앱을 전혀 실행할 수 없음
        • 확인하기
android {
   compileSdkVersion 28
   defaultConfig {
       applicationId "com.example.android.diceroller"
       minSdkVersion 19
       targetSdkVersion 28
       versionCode 1
       versionName "1.0"
   }
   
------------------------------------------------------------------------------
compileSdkVersion 28
targetSdkVersion 28
minSdkVersion 19
  • 호환성 확인 
    • MainActivity는 Activity 가 아닌 AppCompatActivity임 -> 다양한 플랫폼 OS 레벨에서 액티비티가 동일하게 표시되는 호환성 클래스
    • import 앞의 + 버튼을 누르면, AppCompatActivity 클래스가 androidx.appcompat.app 패키지에서 import 됨을 알 수 있음
    • androidx는 Android Jetpack 라이브러리의 이름임!
    • 모듈 단위 그래들을 열면 확인할 수 있음
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
   implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
   implementation 'androidx.core:core-ktx:1.0.1'
   implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
   androidTestImplementation 
        'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

https://developer.android.com/codelabs/kotlin-android-training-images-compat?index=..%2F..android-kotlin-fundamentals&hl=ko#0 

 

Comments