1. 핵심 구성요소
여러 액티비티 구성 → Intent로 화면 전환 및 데이터 전달 → 업 네비게이션으로 복귀 → SharedPreferences로 데이터 영속 저장
Review. 인텐트(Intent)
- 인텐트는 다른 액티비티를 실행시키거나 액티비티 사이에 간단한 데이터를 전달하는 역할을 한다. 즉, 화면 전환의 핵심 도구이다.
- 데이터를 넣을 때와 꺼낼 때의 타입이 대응되며, 추출 시에는
getXXXExtra()형태의 메서드를 사용한다. (XXX는 데이터 타입)
val intent = Intent(this, ResultActivity::class.java)
intent.putExtra("weight", binding.weightEditText.text.toString())
intent.putExtra("height", binding.heightEditText.text.toString())
startActivity(intent)1.1. 업 네비게이션(Up Navigation)
-
상위(부모) 액티비티로 돌아가는 뒤로가기 기능이다.
-
업 네비게이션
- 매니페스트에
android:parentActivityName=".MainActivity"추가 - → 뒤로가기 화살표 활성화
- 매니페스트에
<activity
android:parentActivityName=".MainActivity" />- 툴바
- activity_result.xml에 Toolbar 추가 후
setSupportActionBar(),setDisplayHomeAsUpEnabled(true)등으로 홈 버튼 노출
setSupportActionBar(binding.toolbar)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)1.2. SharedPreferences
-
SharedPreferences
- 키-값(key-value) 형태로 간단한 데이터를 저장·불러오는 방법이다.
- 앱을 종료했다 다시 실행해도 값이 유지되므로, 마지막에 입력한 값을 자동으로 복원하는 데 사용된다.
-
저장 (saveData)
- 버튼 클릭 시
saveData()호출 - →
getSharedPreferences("my_prefs", MODE_PRIVATE)에putInt로 키·몸무게 저장 후commit()(또는apply())
- 버튼 클릭 시
private fun saveData(height: Int, weight: Int) {
val sharedPref = getSharedPreferences(
"my_prefs", Context.MODE_PRIVATE
)
sharedPref.edit().run {
putInt("KEY_HEIGHT", height)
putInt("KEY_WEIGHT", weight)
commit()
}
}- 불러오기 (loadData)
loadData()에서 저장값을 읽어 EditText에 다시 표시- →
onCreate의setContentView다음에 호출
private fun loadData() {
val pref = PreferenceManager.getDefaultSharedPreferences(this)
val height = pref.getInt("KEY_HEIGHT", 0)
val weight = pref.getInt("KEY_WEIGHT", 0)
if (height != 0 && weight != 0) {
binding.heightEditText.setText(height.toString())
binding.weightEditText.setText(weight.toString())
}
}2. 보조 도구
Review. 뷰 바인딩(View Binding)
- 레이아웃 XML에 선언한 뷰 객체를 코드에서 쉽게 다루기 위한 방법이다.
- 기존의
findViewById()를 쓰지 않고도 뷰에 접근할 수 있게 해준다. - 모듈 수준
build.gradle에viewBinding { enable = true }를 추가하면, 레이아웃 파일마다 대응하는 바인딩 클래스가 자동 생성된다. 이름 규칙은 “XML 파일명의 단어를 대문자로 시작하고 밑줄을 제거한 뒤 ‘Binding’을 붙이는” 방식이다. (예:activity_main.xml → ActivityMainBinding) - 생성된 클래스의
inflate()로 바인딩 객체를 얻고, 뷰는 XML에 지정한 id로 접근한다.
2.1. 벡터 드로어블(Vector Drawable)
-
크기를 키워도 깨지지 않는 벡터 형식의 이미지 리소스이다.
-
앱 개발에서는
- PNG·JPG 같은 비트맵 이미지와
- SVG·EPS 같은 벡터 이미지를 사용하는데, 벡터 드로어블이 후자에 해당한다.
-
실습
res폴더 우클릭 → New → Vector Asset → Clip Art에서 표정 아이콘 선택 → drawable 폴더에 저장tint속성으로 이미지 색상을 변경할 수 있다.- (안 보이면 View all attributes 클릭)
- 오류 시
android:tint→app:tint로 수정한다.
-
안드로이드 5.0부터 기본 지원된다.
-
안드로이드 5.0 미만 지원을 위해
build.gradle의defaultConfig에 다음을 추가한다.
vectorDrawables.useSupportLibrary = true2.2. Toast
- 화면에 잠깐 떴다 사라지는 간단한 알림 메시지이다.
2.3. 아이콘 변경
- 매니페스트
<application>의android:icon,android:roundIcon을 mipmap의 커스텀 아이콘으로 지정