我的货币符号为String
,金额为double
。到目前为止,我正在显示这样的金额:
amount.setText(currency + " " + amount);
在某些地方,我有2 TextView
s的时间显示填充量,介于两者之间:
currency.setText(currency);
amount.setText(amount);
没关系 但是,我正在将此代码移动到具有Android数据绑定的布局文件中,是否有一种简单的方法来格式化和显示android中的金额?
例如symbol[space]amount
,金额应设置为小数点后2位,否则为整数。例如,100将显示为100,而不是100.00,但是123.2将首先显示为123.20以及货币符号($ 123.20,$ 100)。
我知道有几种方法(资源字符串格式,NumberFormat)可以做到这一点(我还没有使用过,只是听说过),但是最简单,最干净的方法是什么?
我试图找到所有2个文本视图并将其转换为单个文本视图,并找到统一的方式来格式化和显示金额。
谢谢你。
受到@Nowshad答案的启发,我可以在没有带有数据绑定库的外部lib的情况下做到这一点。
必要时在布局文件中提供货币和金额:
<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}" />
并提供绑定适配器:
@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);
}
简单高效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句