레트로핏을 활용하여 서버에서 받은 응답 리스트 개수에 따라서 동적으로 레이아웃을 설정해주려고 한다.
acativity_main.xml
레이아웃을 추가 할 부모 레이아웃을 먼저 만들어줍니다.
부모 레이아웃은 id는 petLayout으로 설정했습니다.
activity_sub.xml
SubActivity는 부모 레이아웃안에 동적으로 생성할 레이아웃을 정의해줍니다.
id는 childPetLayout으로 설정했습니다.
<?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=".vector.VectorChoicePet"
android:orientation="vertical"
android:background="@color/white">
<LinearLayout
android:id="@+id/childPetLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:orientation="horizontal"
android:visibility="visible">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="15dp">
<TextView
android:id="@+id/choicePetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textStyle="bold"/>
<TextView
android:id="@+id/choicePetAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />
<TextView
android:id="@+id/choicePetBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.Kt 파일
서버에서 응답 받은 결과 개수에 따라 for문을 반복합니다.
데이터를 0번째부터 받은 뒤 createLayout이라는 함수에 데이터를 보내주어 레이아웃을 생성하면서 그 레이아웃에 받아온 데이터를 입력해준다.
petLayout.addView(createLayout) //부모 레이아웃에 자식 레이아웃 추가