Lubos Horacek Lubos Horacek - 4 months ago 77
Android Question

Assign percentage to PercentFrameLayout with databinding

Trying to create simple graph with layout using percent support library, but I'm not able to figure out, how to assign percents to view through databinding. Tried returning String "60%", float 0.6f, Float 0.6f, int 60. Nothing works.

<View
android:id="@+id/graph_before"
android:layout_height="@dimen/list_graph_line_height"
android:layout_gravity="center_vertical"
android:background="@color/colorAccent"
app:layout_marginLeftPercent="@{item.percentValueLeft}"
app:layout_widthPercent="@{item.percentValueWidth}"
/>

Answer

Way to do this is by using custom setters in databinding and PercentLayoutInfo:

@BindingAdapter("app:layout_widthPercent")
public static void setWidthPercent(View view, float width) {
    PercentLayoutHelper.PercentLayoutParams params =(PercentLayoutHelper.PercentLayoutParams) view.getLayoutParams();
    PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
    info.weightPercent = width;
}
Comments