기록
[Android] include 태그로 layout 재사용하기 본문
반응형
현재 만들고 있는 노트 앱에서 데이터베이스의 note data를 fetch하는 동안 프로그레스 바를 돌렸다.
이번에 유저 기능을 추가하면서 로그인/회원가입 단계에서도 데이터를 가져올 때 프로그레스 바를 돌리고 싶었다.
이렇게 같은 레이아웃을 반복해서 사용할 때는 xml에서 include라는 태그를 사용하면 레이아웃을 재사용할 수 있다.
사용법
먼저 재사용할 프로그레스바를 새로운 레이아웃 파일로 빼내고, 여러곳에서 프로그레스바를 돌릴 조건을 전달받기 위해 isVisible이라는 변수를 새로 정의했다.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="isVisible"
type="Boolean" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blackTint"
app:isVisible="@{isVisible}" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminateTint="@color/light_pink"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
그리고 해당 레이아웃을 사용할 xml 파일에 다음과 같은 내용을 추가한다.
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto">
...
<include
layout="@layout/loading_overlay"
bind:isVisible="@{viewModel.isLoading}" />
...
위와 같이 include 태그의 layout 속성에 재사용하려는 레이아웃 파일 이름을 기술한다.
그리고 bind 속성으로 loading_overlay.xml에 선언한 변수에 데이터를 로딩 중인지 판별하는 변수를 전달한다.
해당 레이아웃과 연결된 Fragment에 LifeCycleOwner 바인딩은 필수!
반응형
'[Study] > Android' 카테고리의 다른 글
[Android] Navigation action cannot be found in the current destination 오류 해결 (0) | 2022.11.12 |
---|---|
[Android] editText 바깥 부분을 클릭하면 키보드 내려가게 하는 법 (0) | 2022.10.20 |
[Android] LiveData (0) | 2022.09.29 |
[Bug] onMenuItemSelected에서 이전 값을 참조하는 현상 (0) | 2022.09.24 |
[Error] Fragment not associated with a fragment manager. (0) | 2022.09.23 |