BackEnd/안드로이드
[안드로이드] 2일차
summer_light
2023. 8. 2. 18:00
6. 뷰를 이용한 화면 구성
6-1. 화면을 구성하는 방법
1) 액티비티 코드로 화면 구성하기
-
2) 레이아웃 XML파일로 작성하기
- XML 파일에 XML태그들로 명시해 화면을 구성하는 방법
액티비티 코드에서는 아래 코드를 추가하면 된다.
setContentView(R.layout.activity_main)
6-2. 뷰 클래스
- 레이아웃 안에 레이아웃과 버튼 등의 뷰가 섞여있는, 객체를 계층 구조로 만들어 이용하는 패턴을 컴포지트 패턴, 문서 객체 모델이라고 한다.
- @로 시작하면 R.java 파일을 의미 : 따라서 이 표현식은 R.java 파일에 text1 이라는 상수 변수를 추가하라는 의미
android:id="@+id/text1" //XML에 id 속성을 추가하면 R.java 파일에 상수 변수로 추가됨
- 뷰 객체 획득
val textView1 = findViewById<TextView>(R.id.text1)
- 속성값들
invisible vs gone : 둘 다 보이지 않다가 어느 순간이 되면 보이게 하기 위함
- invisible: 보이지 않지만 자리는 차지
- gone: 보이지 않고 자리도 차지하지 않음
*코틀린의 변수는 필드가 아니라 프로퍼티다
- 프로퍼티: 변수에 세터와 게터가 내장되어 있다.
user.name() //직접 접근하는 것 처럼 보여도 실제로는 세터/게터 함수가 호출
6-3. 기본적인 뷰 살펴보기
- TextView
- ImageView
- Button
- CheckBox
- RadioGroup, RadioButton
- EditText
6-4. 뷰 바인딩
- XML 파일에 선언한 뷰 객체를 코드에서 쉽게 이용하는 방법
기존 | 바인딩 사용 |
XML파일에 등록한 뷰를 findViewById() 함수로 얻어 사용, 일일이 가져와야 함 | xml 파일 이름(activity_main.xml)만 한 번 알려주면 뷰 객체를 포함하는 클래스(ActivityMainBinding)가 자동으로 만들어져 그대로 사용할 수 있음, |
* 바인딩 클래스를 만들기 싫다면 XML파일의 루트 태그에 tools.viewBindingIgnore="true" 추가
// 바인딩 객체 획득
val binding = ActivityMainBinding.inflate(layoutInflater)
// 액티비티 화면 출력
setContentView(binding.root) //바인딩 객체의 root 프로퍼티에는 XML의 루트 태그 객체가 자동으로 등록됨
// 뷰 객체 이용
binding.visibleBtn.setOnClickListener { //뷰 객체명은 뷰의 id값
binding.targetView.visibility = View.VISIBLE
}
6-5. 카카오톡 비밀번호 확인 화면 만들기
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/main_desc"
android:textSize="17dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="kkang104@gmail.com"
android:textColor="#CFCFCE"
android:layout_marginTop="10dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#D4D4D3"
android:layout_marginTop="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="비밀번호"
android:inputType="textPassword"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/password_txt"
android:layout_marginTop="10dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="확인"
android:layout_marginTop="16dp"/>
</LinearLayout>