Android 自定义 TextView 以显示货币

标签 android textview decimalformat

我需要为 TextView 设置掩码以将其文本转换为特定样式(货币,虽然是我自己的,但像这样:Rls ###,###,###,###)但我需要稍后能够得到它的原始文本。我该怎么办?

============================================= =======

假设我将把这个字符串传递给 TextView:2120000

它应该被用户看到:Rls 2,120,000

但是 .getText 方法应该返回:2120000

============================================= =======

格式化代码如下:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("Rls ###,###,###,###", symbols);
String prezzo = decimalFormat.format(Integer.parseInt(textTemp));

任何帮助将不胜感激

最佳答案

正确的方法是这样的: 将自定义 TextView 创建为 Java 类

public class RialTextView extends TextView {

    String rawText;

    public RialTextView(Context context) {
        super(context);

    }

    public RialTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RialTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        rawText = text.toString();
        String prezzo = text.toString();
        try {

            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator(',');
            DecimalFormat decimalFormat = new DecimalFormat("###,###,###,###", symbols);
            prezzo = decimalFormat.format(Integer.parseInt(text.toString()));
        }catch (Exception e){}

        super.setText(prezzo, type);
    }

    @Override
    public CharSequence getText() {

        return rawText;
    }
}

并且在 XML 中而不是 <TextView标签 使用这样的东西:

<com...RialTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Price"
        android:id="@+id/tv_itemgriditems_Price"
        android:layout_below="@+id/tv_itemgriditems_Remain"
        android:layout_centerHorizontal="true"
        android:textSize="15sp"
        />

关于Android 自定义 TextView 以显示货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877167/

相关文章:

android - 启用飞行模式而不禁用android中的wifi和蓝牙

Android 小部件设置 android :updatePeriodMillis programmatically

Android 简单的 TextView 动画

java - 如何在获取百分比符号时避免 UnsupportedOperationException?

Java DecimalFormat 转为 double

java - DecimalFormat - 无小数分隔符

android - 显示上一个 fragment

android - 在 android 模拟器中运行 react-native

java - 克隆 textview 以将其附加到 ViewGroup

android - 在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度