android 데이터바인딩 활용(3) - BindingAdapter

데이터바인딩에서 BindingAdapter를 사용하는 법을 알아보겠습니다.

BindingAdapter는 쉽게 xml을 통하여 함수를 호출 할수 있게 제공합니다.

 android 데이터바인딩 활용(1)의 RecyclerView소스에 이어서 진행 하겠습니다.

public class ColorData {

    int color;

    private int nIdx;

    public ColorData(int nIdx)
    {
        this.nIdx = nIdx;
    }

    public int getColor() {

        int nNum = nIdx%3;
        switch (nNum)
        {
            case 0:
                color = Color.RED;
                break;
            case 1:
                color = Color.BLUE;
                break;
            case 2:
                color = Color.YELLOW;
                break;
        }

        return color;
    }
    
}
우선 샘플로 사용할 Data클래스 하나를 만들어 놓겠습니다.

public class SampleDataBindingAdapter {

    @BindingAdapter({"bind:bgcolor"})
    public static void backgroundColor(View view, int nColor) {
        view.setBackgroundColor(nColor);
    }

}
함수만 생각하시면 되고 클래스는 중요한것이 아닙니다.
BindingApter 어노네이션을 통하여  연결을 해줍니다.
빌드시 warning이 있는데 'bind:' 이부분 삭제하시면 없어집니다.
함수를 선언하는데 첫번제 인자는 View의 객체이고
두번째 인자는 받아서 사용하고 하는 값입니다.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <data>
        <variable
            name="data"
            type="kr.co.proj.test.swiperefreshsample.ColorData"/>

    </data>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:bgcolor="@{data.color}"
        >
        <TextView
            android:id="@+id/text_Item"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"

            />
    </RelativeLayout>
</layout>
xmlns:app="http://schemas.android.com/apk/res-auto"을 추가합니다.
app:bgcolor 에서 보이듯이 bind한 함수를 호출 할수 있습니다.
위에 만들어 두었던 ColorData클래스의 값을 사용 할수 있도록 선언후
bgcolor에 값을 지정합니다.
data.color에 보이듯이 변수 참조는 '.'을 이용해서 참조 합니다.



소스부분에서 binding객체에 setData라는 함수가 존재 하는것을 볼수 있습니다.
저부분에 값을 셋팅해 주면 원하는 값으로 바꿀수 있습니다.

@Override
    public void onBindViewHolder(BindingHolder holder, int position) {

        holder.binding.textItem.setText("Binding Item "+ position);
        holder.binding.setData(new ColorData(position));
    }
ColorData라는 객체를 생성해서 셋팅해주면 우리가 원하는 값으로 볼수 있습니다.

위의 소스는 간단히 구현된 소스이고 굳이 저걸 저렇게 복잡하게 안써도 되는데라고
생각 할수도 있지만 예제는 예제입니다.
위의 방식을 활용한다면 복잡한 레이아웃과 소스를 효율적이 더 깔끔하게 사용할수 있을 것 입니다.

댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

스타트업 성장 곡선 The Startup Curve

현수막/명함 등 인쇄물 디자인하기

SPA(Sigle Page Applications) 란 무엇인가?