シンボル編集ボックスなしの通貨入力
-
28-10-2019 - |
質問
Androidアプリの正規表現を作成しようとしているので、この質問に対する一番の回答のように通貨がフォーマットされます。
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
cashAmountEdit.setText(cashAmountBuilder.toString());
}
}
その例が数字の前にドルのシンボルを引いただけで除外したのと同じ形式を持ちたいと思っていますが、それを達成するためにそのコードを変更する方法については本当にわかりませんか、それとも代替方法がありますか?
編集: :私にとって明らかなコメントの後、それは私のコードのこの特定の部分ではないかもしれません。正規表現の空白のスペースのドル記号を変更し、数字の前に空白のスペースに入ることで、非常に愚かなトレーニングを使用してこれを機能させることができます。回避します。
private TextWatcher billWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
billBox.setText(cashAmountBuilder.toString());
billBox.setTextKeepState(cashAmountBuilder.toString());
Selection.setSelection(billBox.getText(), cashAmountBuilder.toString().length());
}
}
ボックス用のXML
<EditText
android:id="@+id/billBox"
android:layout_width="152dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/billText"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:digits="0123456789."
android:gravity="right"
android:inputType="numberDecimal" />
解決
あなたが持っている: <EditText ... android:digits="0123456789." ... />
それでもあなたの正規表現はあります \\$(\\d{1,3}...
. 。これは、「ドル記号とその後の数字が増える」に変換されます。
システムは、ドル記号が存在することを要求しているが、XMLでそれを禁止することを混乱させていると思います。
私はあなたの正規表現の最初の部分を取り出し、ユーザーにドルのサインを入れます。
他のヒント
この行を削除します
cashAmountBuilder.insert(0, '$');
ドルシンボルを取り出すために必要なのは、この行を取り出すことだけです。CashAmountBuilder.Insert(0、 '$');。
私はあなたがシステムがすでにあなたのためにできることをやりすぎようとしていると思います。通貨価値を内部的に倍に維持し、表示したいときにのみフォーマットする場合、はるかに簡単です。このリンクの私のソリューションを参照してください。それは助けになるかもしれません。通貨編集質問の回答