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

时间:2016-08-08 16:51:23

标签: android

我想有一个编辑文本,可以在数字前自动输入美元符号。 Android Studio

实施例 $ 500

修改

使用编辑文本时(点击时)应该添加$。货币将以加元计算。然而,美元符号将作为该领域的提醒

5 个答案:

答案 0 :(得分:6)

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

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) {}
   });
}

答案 1 :(得分:1)

这个想法是允许在保持货币格式的同时输入货币金额。例如: 在空的输入字段中输入1,然后输出应为$ 0.01。如果我再加上一个数字(例如0),则输出字符串应为$ 0.10。再加上一个数字(例如5),将得出$ 1.05。等等...

这里有一些示例代码,可将货币格式添加到edittext字段的on文本更改侦听器上。

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输入字段

TextInputEditText mCashAmount = mView.findViewById(R.id.txtInput_CashAmount);
mCashAmount.addTextChangedListener(new NumberTextWatcher(mCashAmount));

答案 2 :(得分:0)

将EditText和提示文本包装在视图中并在其上设置自定义背景。

<强> dialog_input.xml

       <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:background="@drawable/bg_text_border_round_corners"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/_31sdp"
                android:fontFamily="@font/sf_pro_text_medium"
                android:textStyle="bold"
                android:text="£"
                android:textColor="@android:color/black"
                android:layout_gravity="center"/>

            <EditText
                android:id="@+id/amount_txt"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:textSize="30dp"
                android:textStyle="bold"
                android:inputType="number"
                android:textColor="@android:color/black"
                android:background="@android:color/transparent"
                android:layout_gravity="center"/>

        </LinearLayout>

<强> bg_text_border_round_corners.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="@android:color/white" />
    <stroke android:width="1dip" android:color="#33000000"/>
    <corners android:radius="5dp"/>
</shape>

我的对话框输出

Output Example

答案 3 :(得分:0)

我的解决方案不使用kotlin和数据绑定(但实际上本质在于文本观察器):

XML部分:

 <EditText
        ...
        android:addTextChangedListener="@{viewModel.currencyTextWatcher}"
        android:inputType="number"
        android:digits="$1234567890"
        />

TextWatcher实现:

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 
}

答案 4 :(得分:-1)

editText.setText("$");

当用户点击editText然后editText预填充“$”符号,但缺点是用户可以删除“$”符号。

此问题的另一个解决方案是,将editText设置为left drawable为“$”或“$ image”。当用户触发save或submit等操作时,请在editText之前添加“$”。

String temp = "$";
String finalString = temp + editText.getText().toString();