この質問に対する一番の回答のように通貨がフォーマットされるように、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" />