kirtan403 kirtan403 - 3 months ago 70
Android Question

How to display formatted amounts in TextView?

I have a currency symbol in

String
and an amount in
double
. Till now I am showing amounts like this:

amount.setText(currency + " " + amount);


And at some places I have 2
TextView
s to display amount with padding in between:

currency.setText(currency);
amount.setText(amount);


Which is fine. But, I am moving this code to the layout files with android data-binding and is there an easy way to format and show amounts in android?

Like
symbol[space]amount
where amount should be formatted with 2 decimal points if present, else whole number. For example, 100 will be displayed as 100, and not 100.00, but 123.2 will be displayed as 123.20 along with the currency symbol at first ($ 123.20, $ 100).

I know there are several ways(resource string format, NumberFormat) I can do that(I have not yet used any of them, just heard of them), but what will be the easiest and cleanest way to do this?

I am trying to find and convert all the 2 text views to single one and finding unified way to format and display amounts.

Thank you.

Answer

Inspired by the @Nowshad's answer, I can do that without external lib with data-binding library.

Provide currency and amount in layout files whenever required:

          <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="end"
                android:textAppearance="@style/TextAppearance.AppCompat.Large"
                app:amount="@{amount}"
                app:currency="@{currency}" />

And provide a binding adapter:

@BindingAdapter({"currency", "amount"})
    public static void setCurrencyAndAmount(TextView textView, String currency, double amount) {
        SpannableString spannableString = new SpannableString(currency + " " +
                new DecimalFormat("#.##").format(amount));

        spannableString.setSpan(new RelativeSizeSpan(0.6f), 0, 1, 0);

        textView.setText(spannableString);
    }

Simple and efficient.