の最小値と最大値を定義したいと思いますEditText
。
たとえば、誰かが月の値を入力しようとした場合、その値は 1 ~ 12 の間でなければなりません。
を使用して実行できますがTextWatcher
、レイアウトファイルまたは他の場所で実行する方法が他にあるかどうか知りたいです。
編集:文字数を制限したくありません。値を制限したい。たとえば、EditText
12 を入力するときに w 文字を制限すると受け入れられますが、22 を入力すると、入力中に受け入れてはなりません。
の最小値と最大値を定義したいと思いますEditText
。
たとえば、誰かが月の値を入力しようとした場合、その値は 1 ~ 12 の間でなければなりません。
を使用して実行できますがTextWatcher
、レイアウトファイルまたは他の場所で実行する方法が他にあるかどうか知りたいです。
編集:文字数を制限したくありません。値を制限したい。たとえば、EditText
12 を入力するときに w 文字を制限すると受け入れられますが、22 を入力すると、入力中に受け入れてはなりません。
最初にこのクラスを作成します:
package com.test;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
次に、 Activity からこれを使用します。
EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});
これにより、ユーザーは 1 から 12 までの値のみを入力できます。
編集 :
で編集テキストを設定しますandroid:inputType="number"
。
ありがとう。
Pratik のコードには小さなエラーがあります。たとえば、値が 10 で、最初に 1 を追加して 110 にする場合、フィルター関数は新しい値を 101 として扱います。
これを修正するには、以下を参照してください。
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Removes string that is to be replaced from destination
// and adds the new string in.
String newVal = dest.subSequence(0, dstart)
// Note that below "toString()" is the only required:
+ source.subSequence(start, end).toString()
+ dest.subSequence(dend, dest.length());
int input = Integer.parseInt(newVal);
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
@Patrikのソリューションと@Zacの追加について私が見たもののうち、提供されたコードにはまだ大きな問題があります:
min==3
1 または 2 で始まる数字を入力できない場合(例: 15、23)すべての数字が 1、2、3 で始まる必要があるため、何も入力でき
ない場合...min>=10
私の理解では、ユーザーが正の数を入力すると値が大きくなり、簡単EditText
にInputFilterMinMax
オンザフライ テストを実行して、制限に達したか範囲外になったかを確認し、準拠していないエントリをブロックします。min 値のテストは別の話です。ユーザーが入力を終了したかどうかを確認できないため、ブロックするかどうかを判断できないからです。
これはまさにOPが要求したものではありませんが、検証目的で、ユーザーの入力が終了したと仮定してフォーカスを失ったときに最小値を再テストするソリューションで、InputFilter
最大値をテストするために組み合わせました。OnFocusChangeListener
EditText
package test;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMax implements InputFilter {
private int max;
public InputFilterMax(int max) {
this.max = max;
}
public InputFilterMax(String max) {
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
String replacement = source.subSequence(start, end).toString();
String newVal = dest.toString().substring(0, dstart) + replacement +dest.toString().substring(dend, dest.toString().length());
int input = Integer.parseInt(newVal);
if (input<=max)
return null;
} catch (NumberFormatException nfe) { }
//Maybe notify user that the value is not good
return "";
}
}
とOnFocusChangeListenerMin
package test;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnFocusChangeListener;
public class OnFocusChangeListenerMin implements OnFocusChangeListener {
private int min;
public OnFocusChangeListenerMin(int min) {
this.min = min;
}
public OnFocusChangeListenerMin(String min) {
this.min = Integer.parseInt(min);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
String val = ((EditText)v).getText().toString();
if(!TextUtils.isEmpty(val)){
if(Integer.valueOf(val)<min){
//Notify user that the value is not good
}
}
}
}
}
次に、Activity でInputFilterMax
とOnFocusChangeListenerMin
をEditText
メモに設定しonFocusChangeListener
ます。
mQteEditText.setOnFocusChangeListener( new OnFocusChangeListenerMin('20');
mQteEditText.setFilters(new InputFilter[]{new InputFilterMax(getActivity(),'50')});
Pratik と Zac の回答の拡張。Zac は、彼の回答で Pratik の小さなバグを修正しました。しかし、コードが負の値をサポートしていないことに気付きました。NumberFormatException がスローされます。これを修正し、MIN が負になるようにするには、次のコードを使用します。
次の行 (太字) を他の 2 行の間に追加します。
newVal = newVal.substring(0, dstart) + source.toString()+ newVal.substring(dstart, newVal.length());
if(newVal.equalsIgnoreCase("-") && min < 0) null を返します。
int 入力 = Integer.parseInt(newVal);
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Remove the string out of destination that is to be replaced
String newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
// Add the new string in
newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
//****Add this line (below) to allow Negative values***//
if(newVal.equalsIgnoreCase("-") && min < 0)return null;
int input = Integer.parseInt(newVal);
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return "";
}
-90:90 のような負の数値の範囲が必要な場合は、このソリューションを使用できます。
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
String stringInput = dest.toString() + source.toString();
int value;
if (stringInput.length() == 1 && stringInput.charAt(0) == '-') {
value = -1;
} else {
value = Integer.parseInt(stringInput);
}
if (isInRange(min, max, value))
return null;
} catch (NumberFormatException nfe) {
}
return "";
}
private boolean isInRange(int min, int max, int value) {
return max > min ? value >= min && value <= max : value >= max && value <= min;
}
}
私は自分の答えを見つけました。大変遅くなりましたが、シェアしたいと思います。このインターフェースを実装します:
import android.text.TextWatcher;
public abstract class MinMaxTextWatcher implements TextWatcher {
int min, max;
public MinMaxTextWatcher(int min, int max) {
super();
this.min = min;
this.max = max;
}
}
そして、アクティビティ内で次のように実装します。
private void limitEditText(final EditText ed, int min, int max) {
ed.addTextChangedListener(new MinMaxTextWatcher(min, max) {
@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 str = s.toString();
int n = 0;
try {
n = Integer.parseInt(str);
if(n < min) {
ed.setText(min);
Toast.makeText(getApplicationContext(), "Minimum allowed is " + min, Toast.LENGTH_SHORT).show();
}
else if(n > max) {
ed.setText("" + max);
Toast.makeText(getApplicationContext(), "Maximum allowed is " + max, Toast.LENGTH_SHORT).show();
}
}
catch(NumberFormatException nfe) {
ed.setText("" + min);
Toast.makeText(getApplicationContext(), "Bad format for number!" + max, Toast.LENGTH_SHORT).show();
}
}
});
}
これは非常に簡単な答えですが、もしあれば教えてください。
@Pratik Sharmas コードを拡張して、int の代わりに BigDecimal オブジェクトを使用するようにしました。これにより、より大きな数値を受け入れ、EditText 内の数値ではない書式 (スペース、コンマ、ピリオドなどの通貨書式など) を考慮できるようになります。
編集: この実装では、通貨に使用したため、BigDecimal に設定された最小有効数字として 2 が設定されていることに注意してください (MIN_SIG_FIG 定数を参照)。独自の実装に合わせて、必要に応じて MIN_SIG_FIG 定数を変更します。
public class InputFilterMinMax implements InputFilter {
private static final int MIN_SIG_FIG = 2;
private BigDecimal min, max;
public InputFilterMinMax(BigDecimal min, BigDecimal max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = new BigDecimal(min);
this.max = new BigDecimal(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
int dend) {
try {
BigDecimal input = formatStringToBigDecimal(dest.toString()
+ source.toString());
if (isInRange(min, max, input)) {
return null;
}
} catch (NumberFormatException nfe) {
}
return "";
}
private boolean isInRange(BigDecimal a, BigDecimal b, BigDecimal c) {
return b.compareTo(a) > 0 ? c.compareTo(a) >= 0 && c.compareTo(b) <= 0
: c.compareTo(b) >= 0 && c.compareTo(a) <= 0;
}
public static BigDecimal formatStringToBigDecimal(String n) {
Number number = null;
try {
number = getDefaultNumberFormat().parse(n.replaceAll("[^\\d]", ""));
BigDecimal parsed = new BigDecimal(number.doubleValue()).divide(new BigDecimal(100), 2,
BigDecimal.ROUND_UNNECESSARY);
return parsed;
} catch (ParseException e) {
return new BigDecimal(0);
}
}
private static NumberFormat getDefaultNumberFormat() {
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
nf.setMinimumFractionDigits(MIN_SIG_FIG);
return nf;
}
最大制限のみを気にする場合は、以下の行に追加してください
android:maxLength="10"
最小制限を追加する必要がある場合は、この方法でこのようにすることができます。この場合、最小制限は 7 です。ユーザーは、最小制限と最大制限の間 (8 から 10 の間) の文字を入力するように制限されています。
public final static boolean isValidCellPhone(String number){
if (number.length() < 8 || number.length() >10 ) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(number).matches();
}
}
ユーザーが開始時に 01 を入力するように制限する必要がある場合は、if 条件を次のように変更します
if (!(number.startsWith("01")) || number.length() < 8 || number.length() >10 ) {
.
.
.
}
最後に次のようなメソッドを呼び出します
....else if (!(Helper.isValidMobilePhone(textMobileNo))){
Helper.setEditTextError(etMobileNo,"Invalid Mobile Number");
}......
Kotlin での非常に単純な例:
import android.text.InputFilter
import android.text.Spanned
class InputFilterRange(private var range: IntRange) : InputFilter {
override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int) = try {
val input = Integer.parseInt(dest.toString() + source.toString())
if (range.contains(input)) null else ""
} catch (nfe: NumberFormatException) {
""
}
}
このコードを確認してください
String pass = EditText.getText().toString();
if(TextUtils.isEmpty(pass) || pass.length < [YOUR MIN LENGTH])
{
EditText.setError("You must have x characters in your txt");
return;
}
//continue processing
edittext.setOnFocusChangeListener( new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
// USE your code here
}
edittextおよびtextwatcherを使用したedittextfilteresの詳細については、以下のリンクを使用してください。
@プラティック・シャルマ
負の数をサポートするには、フィルターメソッド内に次のコードを追加します。
package ir.aboy.electronicarsenal;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
int input;
InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
if ((dest.toString() + source.toString()).equals("-")) {
source = "-1";
}
input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException ignored) {
}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
次に、 Activity からこれを使用します。
findViewById(R.id.myEditText).setFilters(new InputFilter[]{ new InputFilterMinMax(1, 12)});
edittext を次のように設定します。
android:inputType="number|numberSigned"
//まだいくつか問題がありますが、ここでは最小値、最大値を任意の範囲 (正または負) で使用できます
// in filter calss
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
// Remove the string out of destination that is to be replaced
int input;
String newVal = dest.toString() + source.toString();
if (newVal.length() == 1 && newVal.charAt(0) == '-') {
input = min; //allow
}
else {
newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
// Add the new string in
newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
input = Integer.parseInt(newVal);
}
//int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
}
return "";
}
//also the filler must set as below: in the edit createview
// to allow enter number and backspace.
et.setFilters(new InputFilter[]{new InputFilterMinMax(min >= 10 ? "0" : String.valueOf(min), max >-10 ? String.valueOf(max) :"0" )});
//and at same time must check range in the TextWatcher()
et.addTextChangedListener(new
TextWatcher() {
@Override
public void afterTextChanged (Editable editable)
{
String tmpstr = et.getText().toString();
if (!tmpstr.isEmpty() && !tmpstr.equals("-") ) {
int datavalue = Integer.parseInt(tmpstr);
if ( datavalue >= min || datavalue <= max) {
// accept data ...
}
}
}
});
ペットプロジェクトを作成していたときに、この問題に遭遇しました。ここでいくつかの回答を読みましたが、おそらくそのうちの1つか2つをコードに採用しました。
悪いニュース:私は非常に汚い方法を使用してこれを行うことができました (理由はわかります)。まだ対処していないバグがいくつかあります (これを書いていたのは午前 2 時頃でした)。たとえば、min
値が 10 の場合、最初から数値を入力できません。
良いニュース: @nnyerges によって言及された先行ゼロのバグを取り除くことができました。値が 0InputFilter
の場合は、0 を 1 つだけ使用します。min
ただし、私の実装の制限は、InputFilter
ユーザーが最初の数字の後にゼロが続きます。たとえば、最初にユーザーがを入力1000
してから削除1
すると、それは になり000
ます。
それは醜いです、そしてそれは私の汚い醜いTextChangedListener
/の使い方が入ってくるところです.(OPはすでに を使ってそれを行うことTextWatcher
ができると言っていましTextWatcher
たが、何でも.ユーザーは小数点記号を入力できます。例: 範囲は、ユーザー入力InputFilter
inputType
numberDecimal
0 - 100
99.99
、ユーザーがセパレーターを削除すると、9999
. 私たちはそれを望んでいませんよね?
また、負の値に対応するようにしました。
私のコードのいくつかの機能には、好むと好まざるとにかかわらず、意味のない s のトリミングが含まれます。たとえば、ユーザーがから0
削除した場合、定義された範囲内にある限り、先頭の s がトリミングされるため、最終結果は 32 になります。ユーザーが負数 ( ) 表記または小数点記号 ( ) を削除しようとすると、削除後の結果の数値がまだ範囲内にあるかどうかがチェックされます。そうでない場合は、最後の値に戻ります。つまり、ユーザーはそのような削除を行うことはできません。ただし、その場合に新しい値をまたはのいずれかに設定したい場合は、それも可能です。1
10032
0
-
.
min
max
注:私はローカリゼーションを気にするのが面倒なので、小数点としてコンマを使用している人は手動で変更する必要があります。
2 番目の注意:コードは非常に乱雑で、おそらくいくつかまたは多くの冗長なチェックがあるため、注意してください。また、私も改善したいので、提案があればお気軽にコメントしてください。今後使う必要があるかもしれません。知るか?
とにかく、ここに行きます。
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
public class InputFilterMinMax implements InputFilter {
private double min, max;
public InputFilterMinMax(double min, double max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Double.parseDouble(min);
this.max = Double.parseDouble(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
String lastVal = dest.toString();
String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
String strInput = source.toString();
double input;
if (strInput.equals("-") && (lastVal.length() == 0 || lastVal.equals("0"))) {
return null;
} else {
input = Double.parseDouble(newVal);
}
if (isInRange(min, max, input)) {
try {
if (lastVal.equals("0") && strInput.equals("0") && !strInput.equals(".")) {
Log.d("Checkpoint 1", "Can't put 0 again.");
return "";
} else if (strInput.equals("0")) {
if (dstart == 0) {
if (lastVal.substring(0, 1).equals("0")) {
Log.d("Checkpoint 2", "Can't put 0 again.");
return "";
} else if (!lastVal.substring(0, 1).equals(".")) {
Log.d("Checkpoint 3", "Can't put 0 in front of them.");
return "";
}
} else {
if (lastVal.substring(0, 1).equals("0") && dstart == 1) {
Log.d("Checkpoint 4", "Can't put 0 again.");
return "";
} else if (lastVal.substring(0, 1).equals("-")) {
if (Double.parseDouble(lastVal) == 0) {
if (!lastVal.contains(".")) {
Log.d("Checkpoint 5", "Can't put 0 here.");
return "";
} else {
if (dstart <= lastVal.indexOf(".")) {
Log.d("Checkpoint 6", "Can't put 0 here.");
return "";
}
}
} else {
if (lastVal.indexOf("0") == 1 && (dstart == 1 || dstart == 2)) {
Log.d("Checkpoint 7", "Can't put 0 here.");
return "";
} else if ((!lastVal.substring(1, 2).equals("0") && !lastVal.substring(1, 2).equals(".")) && dstart == 1) {
Log.d("Checkpoint 8", "Can't put 0 here.");
return "";
}
}
}
}
}
/**
* If last value is a negative that equals min value,
* and user tries to input a decimal separator at the
* very end, ignore it, because they won't be able to
* input anything except 0 after that anyway.
*/
if (strInput.equals(".") && lastVal.substring(0,1).equals("-")
&& Double.parseDouble(lastVal) == min && dstart == lastVal.length()) {
return "";
}
} catch (Exception e) {
}
return null;
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return "";
}
private boolean isInRange(double a, double b, double c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
さて、本当に汚い部分:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements TextWatcher {
private EditText editInput;
/**
* Var to store old value in case the new value is either
* out of range or invalid somehow. This was because I
* needed a double value for my app, which means I can
* enter a dot (.), and that could mean trouble if I decided
* to delete that dot, e.g. assume the range is 0 - 100.
* At first I enter 99.99, the InputFilter would allow that,
* but what if somewhere down the line I decided to delete
* the dot/decimal separator for "fun"?
* Wow, now I have 9999.
* Also, when I delete negative notation, it can produce
* the same problem.
*/
private String oldVal;
private int min, max;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editInput = findViewById(R.id.edt_input);
editInput.addTextChangedListener(this);
min = -1600;
max = 1500;
editInput.setFilters(new InputFilter[]{new InputFilterMinMax(min, max)});
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
oldVal = saveOldValue(s, start);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validateChange(editInput, oldVal);
}
private String saveOldValue(CharSequence s, int start) {
String oldVal = s.toString();
if (oldVal.contains(".") && start == oldVal.indexOf(".") && start != oldVal.length() - 1) {
return oldVal;
} else if (oldVal.contains("-") && start == oldVal.indexOf("-") && start != oldVal.length() - 1) {
return oldVal;
}
return null;
}
private void validateChange(EditText editText, String oldVal) {
String strNewVal = editText.getText().toString().trim();
boolean isChanged = false;
if (strNewVal.indexOf("0") == 0 || (strNewVal.indexOf("-") == 0 && strNewVal.indexOf("0") == 1)) {
if (strNewVal.contains(".")) {
while ((strNewVal.indexOf("0") == 0 && strNewVal.indexOf(".") != 1 && strNewVal.length() > 2) ||
(strNewVal.indexOf("0") == 1 && strNewVal.indexOf(".") != 2 && strNewVal.length() > 3)) {
Log.d("Trimming 0", "");
strNewVal = strNewVal.replaceFirst("0", "");
isChanged = true;
}
} else if (!strNewVal.contains(".")) {
while (strNewVal.indexOf("0") == 0 && strNewVal.length() > 1) {
Log.d("Trimming 0", "");
strNewVal = strNewVal.replaceFirst("0", "");
isChanged = true;
}
if (Double.parseDouble(strNewVal) > max) {
editText.setText(oldVal); // Or, you can set it to max values here.
return;
}
}
}
if (strNewVal.indexOf(".") == 0) {
strNewVal = "0" + strNewVal;
isChanged = true;
}
try {
double newVal = Double.parseDouble(strNewVal);
Log.d("NewVal: ", String.valueOf(newVal));
if (newVal > max || newVal < min) {
Log.d("Over Limit", "Let's Reset");
editText.setText(oldVal); // Or, you can set it to min or max values here.
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (isChanged) {
editText.setText(strNewVal);
}
}
}
これが私が使用した方法です。負の数に対して機能しています
まず、次のコードで MinMaxFIlter.java クラスを作成します。
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
/**
* Created by 21 on 4/5/2016.
*/
public class MinMaxFilter implements InputFilter {
private double mIntMin, mIntMax;
public MinMaxFilter(double minValue, double maxValue) {
this.mIntMin = minValue;
this.mIntMax = maxValue;
}
public MinMaxFilter(String minValue, String maxValue) {
this.mIntMin = Double.parseDouble(minValue);
this.mIntMax = Double.parseDouble(maxValue);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
Boolean isNeg = false;
String provi = dest.toString() + source.toString();
if("-".equals(provi.substring(0,1))){
if(provi.length()>1) {
provi = provi.substring(1, provi.length());
isNeg = true;
}
else{
if("".equals(source)){
return null;
}
return "-";
}
}
double input = Double.parseDouble(provi);
if(isNeg){input = input * (-1);}
if (isInRange(mIntMin, mIntMax, input)) {
return null;
}
} catch (Exception nfe) {}
return "";
}
private boolean isInRange(double a, double b, double c) {
if((c>=a && c<=b)){
return true;
}
else{
return false;
}
}
}
次に、フィルターを作成して、次のように edittext に設定します。
EditText edittext = new EditText(context);
editext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
eInt.setFilters(new InputFilter[]{new MinMaxFilter(min, max)});
Pratik の回答に追加するために、ユーザーが最小 2 桁、たとえば 15 ~ 100 を入力できる修正バージョンを次に示します。
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
if(end==1)
min=Integer.parseInt(source.toString());
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {
}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}}
追加: if(end==1) min=Integer.parseInt(source.toString());
お役に立てれば。理由なしに反対票を投じないでください。