EditTextのnumberDecimal inputTypeでの小数点区切りコンマ( '、')


133

inputType numberDecimal中にはEditText、ドットを使用しています「」小数点として。ヨーロッパでは、代わりにコンマ「、」を使用するのが一般的です。私のロケールはドイツ語として設定されていますが、小数点は「。」のままです。

小数点記号としてカンマを取得する方法はありますか?



1
このバグは最終的にAndroid Oで修正されました:issuetracker.google.com/issues/36907764
Lovis

彼らはそれが修正されたと言いますが、それが修正されたことを確認できませんか?あなたはできる?
セバスチャン2017

5
少なくともAndroid 8.1(別名LineageOS 15.1)を実行しているNexus 4では、これが修正されていないことを確認できます。Settings-> Languageをフランス語(フランス)に設定すると、android:inputType = "numberDecimal"を含むEditTextは、 '、'(コンマ)セパレーターを提供しますが、コンマの受け入れを拒否します。提供された「。」(小数点)を受け付けます。このバグが最初に報告されてから9年以上が経過しています。それはある種の記録ですか?ラメ。
ピート

回答:


105

(Googleがこのバグを修正するまで)回避策は、EditTextwith android:inputType="numberDecimal"とを使用することandroid:digits="0123456789.,"です。

次に、次のafterTextChangedを使用して、TextChangedListenerをEditTextに追加します。

public void afterTextChanged(Editable s) {
    double doubleValue = 0;
    if (s != null) {
        try {
            doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
        } catch (NumberFormatException e) {
            //Error
        }
    }
    //Do something with doubleValue
}

1
キーボードに表示するコンマ(、)の@Zoombieは、デバイスで設定されている言語によって異なります。入力のタイプがnumberDecimalで、言語が英語(米国)の場合、Nexusデバイスで表示されます(参照)。Nexus以外のデバイスはこれを尊重しない可能性があります
hcpl

11
動作しますが、「24,22.55」のようなテキストを通過させることに注意してください。これを修正するには、検証を追加する必要があるかもしれません!
dimsuz 2014年

8
これはまだ先ですか?
Willi Mentzel 2015年

さらに良いのは、char localizedSeparator = DecimalFormatSymbols.getInstance()。getDecimalSeparator();を使用することです。localizedFloatString = localizedFloatString.replace( '。'、localizedSeparator);
サウザートン

4
これは、あるバグを別のバグと交換しているようです。上で実装したように、これはの代わりにを使用するロケールで機能します。世界中でより一般的な逆を犠牲にして。@southertonの微調整はそれを助けますが、ユーザーがを押すと驚かれる可能性があります。とがあり、入力に表示されます。
Nick

30

ここで提供される「数字」ソリューションのバリエーション:

char separator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));

ロケール区切り文字を考慮に入れます。


これは、元の質問に対する最も明確な答えです。ありがとう
peter.bartos 2017年

これをonCreate()に配置します。これが、私見です。
TechNyquist 2017

6
私はこれが好きですが、注意してください...ユーザーのロケールを気にしないキーボードがあるため、,キーボードにキーがないユーザーがいます。例:Samsungキーボード(KitKat)。
Brais Gabin 2017年

2
これにより、小数点の重複が許可されます。それを処理するには、以下の回答を参照してください:stackoverflow.com/a/45384821/6138589
Esdras Lopez

19

EditTextのコード通貨マスクに続く($ 123,125.155)

XMLレイアウト

  <EditText
    android:inputType="numberDecimal"
    android:layout_height="wrap_content"
    android:layout_width="200dp"
    android:digits="0123456789.,$" />

コード

EditText testFilter=...
testFilter.addTextChangedListener( new TextWatcher() {
        boolean isEdiging;
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
        @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override public void afterTextChanged(Editable s) {
            if(isEdiging) return;
            isEdiging = true;

            String str = s.toString().replaceAll( "[^\\d]", "" );
            double s1 = Double.parseDouble(str);

            NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
            ((DecimalFormat)nf2).applyPattern("$ ###,###.###");
            s.replace(0, s.length(), nf2.format(s1));

            isEdiging = false;
        }
    });

16

これはAndroid SDKの既知のバグです。唯一の回避策は、独自のソフトキーボードを作成することです。実装例はここにあります


15
4年後に何かニュースはありますか?
Antonio Sesto 2015年

Xamarin.Formsでもこれを体験します。カルチャは{se-SV}で、テンキーにはボット "、"(小数点記号)および "。"が表示されます。(千のグループ区切り文字)しかし、「、」を押しても、テキストフィールドには何も入力されず、イベントは発生しません
joacar

バグがまだ存在していることを確認できます。
Lensflare 2018

Android O開発者プレビューで修正
R00We

6

EditTextをプログラムでインスタンス化している場合、Martinsの回答は機能しません。私は先に進みDigitsKeyListener、カンマとピリオドの両方を小数点区切り文字として使用できるように、API 14のインクルードクラスを変更しました。

これを使用するには、呼び出しsetKeyListener()EditText、例えば

// Don't allow for signed input (minus), but allow for decimal points
editText.setKeyListener( new MyDigitsKeyListener( false, true ) );

ただし、TextChangedListenerコンマをピリオドに置き換える場合は、マーティンのトリックを使用する必要があります。

import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.view.KeyEvent;

class MyDigitsKeyListener extends NumberKeyListener {

    /**
     * The characters that are used.
     *
     * @see KeyEvent#getMatch
     * @see #getAcceptedChars
     */
    private static final char[][] CHARACTERS = new char[][] {
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', ',' },
    };

    private char[] mAccepted;
    private boolean mSign;
    private boolean mDecimal;

    private static final int SIGN = 1;
    private static final int DECIMAL = 2;

    private static MyDigitsKeyListener[] sInstance = new MyDigitsKeyListener[4];

    @Override
    protected char[] getAcceptedChars() {
        return mAccepted;
    }

    /**
     * Allocates a DigitsKeyListener that accepts the digits 0 through 9.
     */
    public MyDigitsKeyListener() {
        this(false, false);
    }

    /**
     * Allocates a DigitsKeyListener that accepts the digits 0 through 9,
     * plus the minus sign (only at the beginning) and/or decimal point
     * (only one per field) if specified.
     */
    public MyDigitsKeyListener(boolean sign, boolean decimal) {
        mSign = sign;
        mDecimal = decimal;

        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);
        mAccepted = CHARACTERS[kind];
    }

    /**
     * Returns a DigitsKeyListener that accepts the digits 0 through 9.
     */
    public static MyDigitsKeyListener getInstance() {
        return getInstance(false, false);
    }

    /**
     * Returns a DigitsKeyListener that accepts the digits 0 through 9,
     * plus the minus sign (only at the beginning) and/or decimal point
     * (only one per field) if specified.
     */
    public static MyDigitsKeyListener getInstance(boolean sign, boolean decimal) {
        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);

        if (sInstance[kind] != null)
            return sInstance[kind];

        sInstance[kind] = new MyDigitsKeyListener(sign, decimal);
        return sInstance[kind];
    }

    /**
     * Returns a DigitsKeyListener that accepts only the characters
     * that appear in the specified String.  Note that not all characters
     * may be available on every keyboard.
     */
    public static MyDigitsKeyListener getInstance(String accepted) {
        // TODO: do we need a cache of these to avoid allocating?

        MyDigitsKeyListener dim = new MyDigitsKeyListener();

        dim.mAccepted = new char[accepted.length()];
        accepted.getChars(0, accepted.length(), dim.mAccepted, 0);

        return dim;
    }

    public int getInputType() {
        int contentType = InputType.TYPE_CLASS_NUMBER;
        if (mSign) {
            contentType |= InputType.TYPE_NUMBER_FLAG_SIGNED;
        }
        if (mDecimal) {
            contentType |= InputType.TYPE_NUMBER_FLAG_DECIMAL;
        }
        return contentType;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        CharSequence out = super.filter(source, start, end, dest, dstart, dend);

        if (mSign == false && mDecimal == false) {
            return out;
        }

        if (out != null) {
            source = out;
            start = 0;
            end = out.length();
        }

        int sign = -1;
        int decimal = -1;
        int dlen = dest.length();

        /*
         * Find out if the existing text has '-' or '.' characters.
         */

        for (int i = 0; i < dstart; i++) {
            char c = dest.charAt(i);

            if (c == '-') {
                sign = i;
            } else if (c == '.' || c == ',') {
                decimal = i;
            }
        }
        for (int i = dend; i < dlen; i++) {
            char c = dest.charAt(i);

            if (c == '-') {
                return "";    // Nothing can be inserted in front of a '-'.
            } else if (c == '.' ||  c == ',') {
                decimal = i;
            }
        }

        /*
         * If it does, we must strip them out from the source.
         * In addition, '-' must be the very first character,
         * and nothing can be inserted before an existing '-'.
         * Go in reverse order so the offsets are stable.
         */

        SpannableStringBuilder stripped = null;

        for (int i = end - 1; i >= start; i--) {
            char c = source.charAt(i);
            boolean strip = false;

            if (c == '-') {
                if (i != start || dstart != 0) {
                    strip = true;
                } else if (sign >= 0) {
                    strip = true;
                } else {
                    sign = i;
                }
            } else if (c == '.' || c == ',') {
                if (decimal >= 0) {
                    strip = true;
                } else {
                    decimal = i;
                }
            }

            if (strip) {
                if (end == start + 1) {
                    return "";  // Only one character, and it was stripped.
                }

                if (stripped == null) {
                    stripped = new SpannableStringBuilder(source, start, end);
                }

                stripped.delete(i - start, i + 1 - start);
            }
        }

        if (stripped != null) {
            return stripped;
        } else if (out != null) {
            return out;
        } else {
            return null;
        }
    }
}

ドキュメントから:KeyListenerは、アプリケーションに独自の画面上のキーパッドがあり、ハードキーボードイベントを処理してそれに一致させたい場合にのみ使用してください。developer.android.com/reference/android/text/method/...
LODA

6

異なるロケールには次を使用できます

private void localeDecimalInput(final EditText editText){

    DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
    DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
    final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());

    editText.addTextChangedListener(new TextWatcher() {

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

        }

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

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(editable.toString().contains(defaultSeperator))
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
            else
                editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
        }
    });
}

これは私にとって最良の解決策ですが、一部の電話(Samsungなど)には、キーボードに「、」コマが表示されない問題があります。だから私はこれをコマとドットの両方を許可するように変更しましたが、それからロケールに応じて置き換えます
Riccardo Casatta

5

次の回避策を使用して、有効な入力としてカンマを含めることもできます。

XMLを通じて:

<EditText
    android:inputType="number"
    android:digits="0123456789.," />

プログラム的に:

EditText input = new EditText(THE_CONTEXT);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789.,"));

このようにして、Androidシステムは数字のキーボードを表示し、カンマの入力を許可します。これが質問に答えることを願っています:)


このソリューションでは、「、」をタップすると編集テキストに「。」が表示されます。
マラヒメネス2016

2

Mono(Droid)ソリューションの場合:

decimal decimalValue = decimal.Parse(input.Text.Replace(",", ".") , CultureInfo.InvariantCulture);

1

次のことができます。

DecimalFormatSymbols d = DecimalFormatSymbols.getInstance(Locale.getDefault());
input.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(5, 2) });
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + d.getDecimalSeparator()));

そして、あなたは入力フィルターを使うことができます:

    public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    DecimalFormatSymbols d = new DecimalFormatSymbols(Locale.getDefault());
    String s = "\\" + d.getDecimalSeparator();
    mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((" + s + "[0-9]{0," + (digitsAfterZero - 1) + "})?)||(" + s + ")?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Matcher matcher = mPattern.matcher(dest);
    if (!matcher.matches())
        return "";
    return null;
}

}


1000から100の間のスペースがある場合、このパターンはフォーマットされた入力を拒否します
Eric Zhao

1

私見この問題に対する最善のアプローチは、InputFilterを使用することです。素敵な要点はここDecimalDigitsInputFilterです。その後、次のことができます:

editText.setInputType(TYPE_NUMBER_FLAG_DECIMAL | TYPE_NUMBER_FLAG_SIGNED | TYPE_CLASS_NUMBER)
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,.-"))
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

それは魅力のように働いています、ありがとう!(上記の非常に多くの間違った解決策の後... :()しかし、私は質問があります:ドット( "。")ではなく画面に表示されるそのコンマ( "、")を達成するにはどうすればよいですか? 。
アビゲイルLa'Fay

1
android:digits = "0123456789、"設定をEditTextに追加できます。また、代わりにDecimalDigitsInputFilterにはnullを返す、あなたは(「 『』。」)source.replaceを返すことができる回答に応じstackoverflow.com/a/40020731/1510222標準キーボードで非表示ドットに方法はありません
ArkadiuszCieśliński19年

1

入力使用をローカライズするには:

char sep = DecimalFormatSymbols.getInstance().getDecimalSeparator();

次に追加します:

textEdit.setKeyListener(DigitsKeyListener.getInstance("0123456789" + sep));

「、」を「」に置き換えることを忘れないでください。したがって、FloatまたはDoubleはエラーなしで解析できます。


1
このソリューションでは、複数のカンマを入力できます
Leo Droidcoder

1

ここの他のすべての投稿には大きな穴が開いていたので、次の解決策を示します。

  • 地域に基づいてコンマまたはピリオドを適用すると、反対のタイプを入力できなくなります。
  • EditTextが何らかの値で始まる場合、必要に応じて正しいセパレーターを置き換えます。

XMLでは:

<EditText
    ...
    android:inputType="numberDecimal" 
    ... />

クラス変数:

private boolean isDecimalSeparatorComma = false;

onCreateで、現在のロケールで使用されているセパレータを見つけます。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    NumberFormat nf = NumberFormat.getInstance();
    if (nf instanceof DecimalFormat) {
        DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
        char decSeparator = sym.getDecimalSeparator();
        isDecimalSeparatorComma = Character.toString(decSeparator).equals(",");
    }
}

また、onCreate、現在の値をロードしている場合は、これを使用して更新します。

// Replace editText with commas or periods as needed for viewing
String editTextValue = getEditTextValue(); // load your current value
if (editTextValue.contains(".") && isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll("\\.",",");
} else if (editTextValue.contains(",") && !isDecimalSeparatorComma) {
    editTextValue = editTextValue.replaceAll(",",".");
}
setEditTextValue(editTextValue); // override your current value

また、onCreate、リスナーの追加

editText.addTextChangedListener(editTextWatcher);

if (isDecimalSeparatorComma) {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));
} else {
    editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
}

editTextWatcher

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

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

    @Override
    public void afterTextChanged(Editable s) {
        String editTextValue = s.toString();

        // Count up the number of commas and periods
        Pattern pattern = Pattern.compile("[,.]");
        Matcher matcher = pattern.matcher(editTextValue);
        int count = 0;
        while (matcher.find()) {
            count++;
        }

        // Don't let it put more than one comma or period
        if (count > 1) {
            s.delete(s.length()-1, s.length());
        } else {
            // If there is a comma or period at the end the value hasn't changed so don't update
            if (!editTextValue.endsWith(",") && !editTextValue.endsWith(".")) {
                doSomething()
            }
        }
    }
};

doSomething()の例、データ操作のために標準期間に変換

private void doSomething() {
    try {
        String editTextStr = editText.getText().toString();
        if (isDecimalSeparatorComma) {
            editTextStr = editTextStr.replaceAll(",",".");
        }
        float editTextFloatValue = editTextStr.isEmpty() ?
                0.0f :
                Float.valueOf(editTextStr);

        ... use editTextFloatValue
    } catch (NumberFormatException e) {
        Log.e(TAG, "Error converting String to Double");
    }
}

0

Androidには、数値フォーマッターが組み込まれています。

あなたは、あなたにこれを追加することができますEditText小数点とカンマを許可する: android:inputType="numberDecimal"android:digits="0123456789.,"

次に、コードのどこかで、ユーザーが[保存]をクリックしたとき、またはテキストが入力された後(リスナーを使用)。

// Format the number to the appropriate double
try { 
    Number formatted = NumberFormat.getInstance().parse(editText.getText().toString());
    cost = formatted.doubleValue();
} catch (ParseException e) {
    System.out.println("Error parsing cost string " + editText.getText().toString());
    cost = 0.0;
}

0

編集中のみコンマをドットに変更することにしました。ここに私のトリッキーで比較的単純な回避策があります:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText editText = (EditText) v; 
            String text = editText.getText().toString();
            if (hasFocus) {
                editText.setText(text.replace(",", "."));
            } else {
                if (!text.isEmpty()) {
                    Double doubleValue = Double.valueOf(text.replace(",", "."));
                    editText.setText(someDecimalFormatter.format(doubleValue));
                }
            }
        }
    });

someDecimalFormatterはロケールに応じてコンマまたはドットを使用します


0

なぜあなたの答えがとても複雑なのか、私にはわかりません。SDKにバグがある場合は、オーバーライドするか、回避する必要があります。

私はその問題を解決する2番目の方法を選択しました。文字列を次のようにフォーマットし、Locale.ENGLISHそれをEditText(空の文字列としても)に配置した場合。例:

String.format(Locale.ENGLISH,"%.6f", yourFloatNumber);

その解決策を追いかけると、結果は表示されているキーボードと互換性があります。次に、浮動小数点数と倍精度数は、プログラミング言語のように、コンマの代わりにドットを使用する方法で機能します。


0

私の解決策は:

  • 主な活動:

    char separator =DecimalFormatSymbols.getInstance().getDecimalSeparator(); textViewPitchDeadZone.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));

  • xmlファイル: android:imeOptions="flagNoFullscreen" android:inputType="numberDecimal"

そしてeditTextのdoubleを文字列として受け取りました。


0

私は提案された修正がSamsung IME(少なくともS6とS9)とLGで機能しないことを確認できます。ロケールに関係なく、小数点を小数点として表示します。GoogleのIMEに切り替えると、これは修正されますが、ほとんどの開発者にとって選択肢にはなりません。

また、SamsungやLGがしなければならない修正であり、古い携帯電話にまでプッシュする必要があるため、これらのキーボードのOreoでは修正されていません。

代わりに、数値キーボードプロジェクトフォークして、IMEのように動作するモードforkを追加しました。詳細については、プロジェクトサンプルを参照してください。これは私にとっては非常にうまく機能しており、バンキングアプリに表示される多くの「PINエントリ」の偽のIMEに似ています。

アプリのスクリーンショットの例


0

8年以上経ちましたが、驚いています。この問題はまだ修正されていません... @Martinが最も支持している回答では複数の区切り文字を入力できる
ためこの単純な問題に苦労しました。つまり、ユーザーは「12 ,,, ,,, 12,1、、21,2、 "
また、2番目の問題は、一部のデバイスではカンマが数字キーボードに表示されないことです(またはドットボタンを複数回押す必要があります)。

前述の問題を解決し、ユーザーが「。」を入力できるようにする私の回避策を次に示します。および '、'ですが、EditTextでは、現在のロケールに対応する唯一の小数点記号が表示されます。

editText.apply { addTextChangedListener(DoubleTextChangedListener(this)) }

そして、テキストウォッチャー:

  open class DoubleTextChangedListener(private val et: EditText) : TextWatcher {

    init {
        et.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        et.keyListener = DigitsKeyListener.getInstance("0123456789.,")
    }

    private val separator = DecimalFormatSymbols.getInstance().decimalSeparator

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        //empty
    }

    @CallSuper
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        et.run {
            removeTextChangedListener(this@DoubleTextChangedListener)
            val formatted = toLocalizedDecimal(s.toString(), separator)
            setText(formatted)
            setSelection(formatted.length)
            addTextChangedListener(this@DoubleTextChangedListener)
        }
    }

    override fun afterTextChanged(s: Editable?) {
        // empty
    }

    /**
     * Formats input to a decimal. Leaves the only separator (or none), which matches [separator].
     * Examples:
     * 1. [s]="12.12", [separator]=',' -> result= "12,12"
     * 2. [s]="12.12", [separator]='.' -> result= "12.12"
     * 4. [s]="12,12", [separator]='.' -> result= "12.12"
     * 5. [s]="12,12,,..,,,,,34..,", [separator]=',' -> result= "12,1234"
     * 6. [s]="12.12,,..,,,,,34..,", [separator]='.' -> result= "12.1234"
     * 7. [s]="5" -> result= "5"
     */
    private fun toLocalizedDecimal(s: String, separator: Char): String {
        val cleared = s.replace(",", ".")
        val splitted = cleared.split('.').filter { it.isNotBlank() }
        return when (splitted.size) {
            0 -> s
            1 -> cleared.replace('.', separator).replaceAfter(separator, "")
            2 -> splitted.joinToString(separator.toString())
            else -> splitted[0]
                    .plus(separator)
                    .plus(splitted.subList(1, splitted.size - 1).joinToString(""))
        }
    }
}

0

シンプルなソリューションで、カスタムコントロールを作成します。(これはXamarin androidで作成されていますが、Javaに簡単に移植できます)

public class EditTextDecimalNumber:EditText
{
    readonly string _numberFormatDecimalSeparator;

    public EditTextDecimalNumber(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        InputType = InputTypes.NumberFlagDecimal;
        TextChanged += EditTextDecimalNumber_TextChanged;
        _numberFormatDecimalSeparator = System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator;

        KeyListener = DigitsKeyListener.GetInstance($"0123456789{_numberFormatDecimalSeparator}");
    }

    private void EditTextDecimalNumber_TextChanged(object sender, TextChangedEventArgs e)
    {
        int noOfOccurence = this.Text.Count(x => x.ToString() == _numberFormatDecimalSeparator);
        if (noOfOccurence >=2)
        {
            int lastIndexOf = this.Text.LastIndexOf(_numberFormatDecimalSeparator,StringComparison.CurrentCulture);
            if (lastIndexOf!=-1)
            {
                this.Text = this.Text.Substring(0, lastIndexOf);
                this.SetSelection(this.Text.Length);
            }

        }
    }
}

0

を使用することもできますinputType="phone"が、その場合は複数,または.存在していることに対処する必要があるため、追加の検証が必要になります。


-1

このソリューションは、ここに書かれた他のソリューションよりも複雑ではないと思います。

<EditText
    android:inputType="numberDecimal"
    android:digits="0123456789," />

このように「。」を押すと ソフトキーボードでは何も起こりません。使用できるのは数字とコンマのみです。


4
これを行うと、「。」を使用するすべてのロケールが壊れます。代わりに。
Nick
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.