Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a double using Android view data bindings?

Tags:

android

Say I have an Earthquake class which has a field public final double magnitude;, and I have a layout similar to this one:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="earthquake" type="com.example.Earthquake"/>
    </data>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="48dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@{String.format(earthquake.magnitude)}" />
        ...
    </LinearLayout>
</layout>

Note I have to use "@{String.format(earthquake.magnitude)}" to use this field, else I get this error:

Cannot find the setter for attribute 'android:text' on android.widget.TextView with parameter type double.

Unfortunately, this results in the double being printed at full accuracy. How can I format the double value that is shown?

like image 950
Adam S Avatar asked May 31 '15 20:05

Adam S


People also ask

What is 2 way data binding in Android?

Stay organized with collections Save and categorize content based on your preferences. The @={} notation, which importantly includes the "=" sign, receives data changes to the property and listen to user updates at the same time.

Can I use both data binding and view binding?

There is nothing ViewBinding can do that DataBinding cannot but it costs longer build times. Remember you don't need to use both, if you are using DataBinding, there is no need adding ViewBinding.


2 Answers

I haven't yet looked at the binding expression language in the M SDK preview, so I might be jumping to conclusions, but if this calls through to the normal String.format() method, then it requires a pattern. Have you tried this?

android:text='@{String.format("%.1f", earthquake.magnitude)}'
like image 145
Barend Avatar answered Oct 13 '22 21:10

Barend


String.valueOf() is also an option:

android:text="@{String.valueOf(earthquake.magnitude)}"
like image 22
Paul Spiesberger Avatar answered Oct 13 '22 21:10

Paul Spiesberger