둥근 모서리를 갖는 단색 배경을 지정하려다 보면 다음과 같이 xml 을 정의한 뒤 View의 배경으로 지정할 수 있다.
(drawable/bg_rounded.xml)
<shape android:shape="rectangle">
<solid android:color="@color/bg_color"/>
<corners android:radius="2dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_rounded">
하지만 다른 뷰에서 색상이나 radius 값을 변경해야하는 경우 이 xml 을 재사용하기는 쉽지 않다.
그래서 Databinding을 활용해보기로 한다.
public class ViewBindingAdapter {
@BindingAdapter(value = {"bgCornerRadius"})
public static void setBackgroundCornerRadius(View view, float cornerRadius){
if(view==null){
return;
}
Drawable drawable = view.getBackground();
cornerRadius *= view.getResources().getDisplayMetrics().density;
GradientDrawable gradientDrawable = GradientDrawableUtil.getGradientDrawable(drawable, cornerRadius);
view.setBackground(gradientDrawable);
}
}
public class GradientDrawableUtil {
public static GradientDrawable getGradientDrawable(Drawable drawable, float cornerRadius){
GradientDrawable gradientDrawable;
if(drawable instanceof GradientDrawable){
gradientDrawable = (GradientDrawable) drawable;
}else{
gradientDrawable = new GradientDrawable();
if(drawable instanceof ColorDrawable){
ColorDrawable colorDrawable = (ColorDrawable) drawable;
gradientDrawable.setAlpha(colorDrawable.getAlpha());
gradientDrawable.setColor(colorDrawable.getColor());
}
}
gradientDrawable.setCornerRadius(cornerRadius);
return gradientDrawable;
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:bgCornerRadius="@{4f}"
android:background="@color/grey">
xml내에서 View 속성에 간단히 radius 값을 입력하는것으로 단색의 둥근 배경을 만들 수 있다.
0개의 댓글