본문 바로가기

코딩/안드로이드

Android View Stub

View Stub란?

 

레이아웃을 include 태그처럼 외부의 layout을 들고오는건데,

 

여타 include 태그와는 다르게 동적으로 필요할 때 inflate 할 수 있는 태그이다.

 

예를 들면

 

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <ViewStub
            android:id="@+id/my_stub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout="@layout/my_inflate_layout" />

    </LinearLayout>

와 같은 main activity layout이 있다고 치자.

 

그리고

 

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/text_view_1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/text_view_2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <TextView
            android:id="@+id/text_view_3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </LinearLayout>

와 같이 my_inflate_layout.xml이 있다고 치자.

 

이렇게 되면, 액티비티에서는

 

View inflatedView = ((ViewStub) findViewById(R.id.my_stub)).inflate();
TextView text1 = inflateView.findViewById(R.id.text_view_1)

와 같이 my_inflate_layout을 ViewStub 태그가 있는 위치에 inflate할 수 있다.

또한 my_inflate_layout의 내부에 있는 View들을 접근하고 싶으면,

위의 코드처럼 inflate의 return으로 얻은 View를 이용해서 findViewById하면 된다.