首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Android编辑文本中自动添加美元符号($)

在Android编辑文本中自动添加美元符号($)
EN

Stack Overflow用户
提问于 2016-08-08 16:51:22
回答 7查看 17.6K关注 0票数 4

我想有一个编辑文本,将自动输入一个美元之前的数字。Android Studio

示例500美元

编辑:

$的添加应该在使用编辑文本时进行(点击时)。这种货币将采用加元。然而,美元标志将作为一个提醒的领域是什么。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2016-08-08 17:04:53

只需添加一个onChange侦听器,并在用户完成输入后插入$。

代码语言:javascript
复制
private EditText yourEditText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    yourEditText = (EditText) findViewById(R.id.yourEditTextId);

    yourEditText.addTextChangedListener(new TextWatcher() {
      @Override
      public void afterTextChanged(Editable s) {
        yourEditText.setText("$" + yourEditText.getText().toString());
      }
      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });
}
票数 8
EN

Stack Overflow用户

发布于 2019-05-07 11:58:31

我的解决方案是取消kotlin和数据库(但实际上实质在文本观察者中):

XML部分:

代码语言:javascript
复制
 <EditText
        ...
        android:addTextChangedListener="@{viewModel.currencyTextWatcher}"
        android:inputType="number"
        android:digits="$1234567890"
        />

TextWatcher实现:

代码语言:javascript
复制
val currencyTextWatcher = object : TextWatcher {
    override fun afterTextChanged(editable: Editable?) {
        when {
            editable.isNullOrEmpty() -> return
            Regex("\\$\\d+").matches(editable.toString()) -> return
            editable.toString() == "$" -> editable.clear()
            editable.startsWith("$").not() -> editable.insert(0, "$")
        }
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit 
}
票数 2
EN

Stack Overflow用户

发布于 2020-01-13 12:34:53

这样做的目的是允许在保持货币格式的同时输入货币金额。例如:在空输入字段中输入1,那么输出应该是$0.01。如果我再添加一个数字(比如0),那么输出字符串应该是$0.10。再加上一位数(比如说5位数),就会产生1.05美元的收益。等等..。

下面是一些示例代码,用于将货币格式添加到编辑文本字段的on文本更改监听器中。

代码语言:javascript
复制
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.text.DecimalFormat;
import java.text.ParseException;

//This class is for entering currency amount while keeping the right format as the user enters values
public class NumberTextWatcher implements TextWatcher {
    private final DecimalFormat dfnd;
    private final EditText et;

    public NumberTextWatcher(EditText editText) {
        dfnd = new DecimalFormat("#,##0.00");
        this.et = editText;
    }

    @Override
    public void afterTextChanged(Editable s) {
        et.removeTextChangedListener(this);
        //After all the text editing, if there is a string to validate - format it
        if (s != null && !s.toString().isEmpty()) {
            try {
                //Take the input string and remove all formatting characters
                String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "").replace("$","").replace(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()), "");
                //Pass the altered string to a number
                Number n = df.parse(v);
                //Get the decimal point correct again
                n = n.doubleValue() / 100.0;
                //Reformat the text with currency symbols, grouping places etc.
                et.setText(dfnd.format(n));
                //Add the Dollar symbol ($)
                et.setText("$".concat(et.getText().toString()));
                //Move the editing cursor back to the right place
                et.setSelection(et.getText().length());

            } catch (NumberFormatException | ParseException e) {
                e.printStackTrace();
            }
        } else //if the input field is empty
        {
            et.setText("$0.00");
        }

        et.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
    }
}

接下来,只需将这个新的事件侦听器类链接到EditText输入字段。

代码语言:javascript
复制
TextInputEditText mCashAmount = mView.findViewById(R.id.txtInput_CashAmount);
mCashAmount.addTextChangedListener(new NumberTextWatcher(mCashAmount));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38834649

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档