03 데이터바인딩(2)

박진영·2022년 12월 30일
0

기존프로젝트

만약 Sample 객체에 Sample색깔을 표현하는 int sampleColor가 있다고 가정하자.
0이면 흰색, 1이면 검은색을 반환해야한다.

그러면 아주 보편적으로는 다음과 같이 할 것이다.

public class Sample{
	...
    private int sampleColor;
    ...
    public String getSampleColorAsText(){
    	return (sampleColor==0) ? "흰색" : "검은색;
    }
}
	

레이아웃 xml파일에서는

<TextView
          ...
          android:text="@{sample.getSampleAsText}"/>

그러나 이는 데이터 관련 처리는 xml에서 처리하겠다는 앞선 데이터 바인딩과 관련이 멀어진다.

데이터바인딩 적용(XML내 데이터 가공)

getSampleColorAsText()부분을 지우고 위 xml 코드를 다음과 같이 수정한다.

android:text="@{(sample.sampleColor == 0) ? &quot;흰색&quot; : &quot;검은색&quot;}

그러나 위의 경우는 보통 상수를 적용해서 구현하기도 함
public class Sample{
	...
    public static final int SAMPLE_COLOR_WHITE = 0;
   	public static final int SAMPLE_COLOR_BLACK = 1;
    ...
}

상수를 어떻게 xml내에서 처리할 수 있을까?

<layout 
        ...>
    <data>
    	<import type="com.example.myapplication.UserProfile"/>
        <variable name="userProfile" type="com.example.myapplication.UserProfile"/>
    </data>
  ...
</layout>

위와 같이 data영역 수정한 후 xml 내부 해당 TextView 코드를 수정한다.

android:text="@{(sample.sampleColor == Sample.SAMPLE_COLOR_WHITE) ? &quot;흰색&quot; : &quot;검은색&quot;}

이미지는 어떻게 xml내에서 처리할 수 있을까? 이미지 처리를 위해 Glide를 사용한다
public class Sample{
	...
    private String sampleImageUrl;
    ...
}
<ImageView
           android:layout_width="100dp"
           android:layout_height="100dp"
           imageUrl="@{sample.sampleImageUrl}"/>

이 때, 외부라이브러리 없이 imageUrl이라는 custom attribute는 binding adapter를 통해 동작을 구현해주면 된다.
binding adapter는 static으로 imageUrl에 대한 메소드를 구현해주면 됨

public class MyBindingAdapter {
    @BindingAdapter("imageUrl")
    public static void loadImageUrl(ImageView view,String url){
        Glide.with(view.getContext()).load(url).into(view);
    }
}

졸업프로젝트 적용

졸프 적용

profile
오늘도 영차🐜

0개의 댓글