AndroidでEditTextの最小値と最大値を定義する方法はありますか?


133

の最小値と最大値を定義しますEditText

たとえば、誰かが月の値を入力しようとする場合、値は1〜12でなければなりません。

私はそれを使ってそれを行うことができますTextWatcherが、レイアウトファイルまたは他の場所でそれを行う他の方法があるかどうか知りたいです。

編集:文字数を制限したくない。値を制限したい。たとえば、EditText12を入力したときに月のw文字を制限した場合はそれが受け入れられますが、22を入力した場合は、入力している間は受け入れられません。


誰かがこれらすべてのタイプの入力フィルターのライブラリー/コレクションを作成する必要があります。その後、全員が一緒に作業してテストできます。一人一人が自分でやるというより。
Zapnologica 2016年

このエディットテキストフィルターを使用して、問題を解決します。フィルター
Taras Smakula 2017

回答:


286

まず、このクラスを作成します。

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

次に、これをアクティビティから使用します。

EditText et = (EditText) findViewById(R.id.myEditText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "12")});

これにより、ユーザーは1〜12の値のみを入力できます。

編集:

edittextをで設定しますandroid:inputType="number"

詳細については、https://www.techcompose.com/how-to-set-minimum-and-maximum-value-in-edittext-in-android-app-development/をご覧ください

ありがとう。


1
@mertaydin確かに。それを試してみて、私の助けが必要なら私に知らせてください。ありがとう。
Pratik Sharma 2013

12
ああ、私は助けが必要です。1930年から1999年の間に値を書き込むときに問題が発生しました。1を書き込むと値が制御され、1は1930年から1999年の間にないため、受け入れません。
mertaydin 2013年

1
@mertaydin申し訳ありませんが、仕事で少し忙しいです。これを検討する時間が少しありました。フィルタークラスに適用されているアルゴリズムを変更する必要があると思います。それが終わったら更新します。
Pratik Sharma

1
の一部の文字sourceは、の一部の文字を置き換えdestます。交換をシミュレートして最終結果を取得し、それを検証する必要があると思います。
SD

3
@Pratik Sharma、これは1900〜2000の範囲に入ると機能しません。何か提案できますか
EminenT

89

Pratikのコードに小さなエラーがあります。たとえば、値が10で、最初に1を追加して110にする場合、フィルター関数は新しい値を101として扱います。

これに対する修正については以下を参照してください:

@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
        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());
        int input = Integer.parseInt(newVal);
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
}

ありがとう、これは私を助けてくれました!
joschplusa 2013年

4
私はこれがより明確であると思います:String replacement = source.subSequence(start, end).toString(); String newVal = dest.subSequence(0, dstart).toString() + replacement + dest.subSequence(dend, dest.length()).toString();
Sven Jacobs

1
+1。このソリューションは、受け入れられるよりも正確です。それを確認するには、たとえば、selectAllOnFocusオプションを有効にしてInputFilterMinMaxを使用し、結果を比較してみてください。
Sash0k 2014年

1
なぜString newVal= dest.toString().substring(0, dstart) + source.toString().substring(start, end) + dest.toString().substring(dend, dest.toString().length());、よりクリーンでクリアに見えますか。
Shishir Gupta

5
OP @mertaydinが@Patrickの回答のコメントで述べたように、この解決策にはまだ重大な欠陥があります。なぜそれが報告されていないのか不思議に思いmin==3ます。
15、23

10

@Patrikのソリューションと@Zacの追加について私が見たもののうち、提供されたコードには大きな問題があります:

場合はmin==3、それが1または2(例:15、23)で始まる任意の番号を入力することは不可能だ
場合はmin>=10、すべての数が1,2,3で開始する必要がありますよう、それは何も入力することは不可能です...

私の理解ではEditText、クラスの単純な使用ではInputFilterMinMax、少なくともmin Valueではなく、の値のmin-max制限を達成することはできません。ユーザーが正の数を入力すると、値が増加し、簡単に実行できるためです。オンザフライテストで、制限に達したか、範囲外になったかを確認し、準拠していないエントリをブロックします。最小値のテストは別の話です。ユーザーが入力を完了したかどうかがわからないため、ブロックする必要があるかどうかを判断できないためです。

それは正確にOPが要求したものではありませんが、検証のために、InputFilter最大値をテストするためにと組み合わせて、ユーザーが入力を完了したと仮定してフォーカスOnFocusChangeListenerEditText失われたときに最小値を再テストするために、これを次のようにしています:

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
            }

        }
    }
}
}

その後の活動にセットInputFilterMaxし、OnFocusChangeListenerMinEditText 注意を:あなたは2分とmaxの両方にすることができますonFocusChangeListener

mQteEditText.setOnFocusChangeListener( new OnFocusChangeListenerMin('20');
mQteEditText.setFilters(new InputFilter[]{new InputFilterMax(getActivity(),'50')});

OnFocusChangeListenerMinが機能していないため、すべての値がゼロから配置されます
EminenT

1
もう少し詳しく教えていただけませんか?ゼロからすべての値を入れるとはどういう意味ですか?
Guerneen4

コードからOnFocusChangeListenerMinは、問題で説明されているように20を超えて機能している必要があります。0、1、2、------ 19などの20未満のすべての値を受け入れます
EminenT

何か解決策を見つけましたか?
EminenT 2015年

検証の目的でOnFoncusChangeListenerを使用しました。私の場合、EditTextにエラーを表示し、値が適切でないことをトーストでユーザーに通知し、新しい値を入力するようにユーザーに招待し if(Integer.valueOf(val)<min){ //Notify user that the value is not good } ます。ユーザーとEditTextを空白に設定、これがあなたの質問に答えるかどうかわかりません
Guerneen4

9

PratikとZacの答えの拡張。ザックは彼の答えでプラティックの小さなバグを修正しました。しかし、コードが負の値をサポートしていないことに気付いたので、NumberFormatExceptionがスローされます。これを修正し、MINが負になるようにするには、次のコードを使用します。

他の2つの行の間に次の行(太字)を追加します。

newVal = newVal.substring(0、dstart)+ source.toString()+ newVal.substring(dstart、newVal.length());

if(newVal.equalsIgnoreCase( "-")&& min <0)return null;

int input = 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 "";
}

5

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

5

@Pratik Sharmasコードを拡張して、intの代わりにBigDecimalオブジェクトを使用して、より大きな数値を受け入れ、EditTextの数値ではないフォーマット(通貨フォーマット、つまりスペース、コンマ、ピリオドなど)を考慮できるようにしました

編集:この実装では、通貨に使用したBigDecimal(MIN_SIG_FIG定数を参照)に設定された最小有効桁数として2があるため、小数点の前には常に2つの先行数値がありました。独自の実装の必要に応じて、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;
}

4

私は自分の答えを見つけました。とても遅いですが、皆さんにお伝えしたいと思います。私はこのインターフェースを実装します:

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

これは非常に簡単な答えです。


int n = 0; 冗長です。Nのデフォルト値は0であるので
ケニーDabiri

1
なぜint n = 0はここで冗長なのですか?ここではローカル変数であり、インスタンス変数ではありません。
User12111111

4

受け入れられた答えに問題があります。

int input = Integer.parseInt(dest.toString() + source.toString());

カーソルをテキストの中央に移動してから何かを入力すると、上記のステートメントは誤った結果を生成します。たとえば、最初に「12」と入力し、次に1と2の間で「0」と入力すると、上記のステートメントでは102ではなく「120」が生成されます。このステートメントを以下のステートメントに変更しました。

String destString = dest.toString();
  String inputString = destString.substring(0, dstart) + source.toString() + destString.substring(dstart);
  int input = Integer.parseInt(inputString);

4

必要な場合はKotlin(ユーティリティを使用)

class InputFilterMinMax: InputFilter {
    private var min:Int = 0
    private var max:Int = 0
    constructor(min:Int, max:Int) {
        this.min = min
        this.max = max
    }
    constructor(min:String, max:String) {
        this.min = Integer.parseInt(min)
        this.max = Integer.parseInt(max)
    }
    override fun filter(source:CharSequence, start:Int, end:Int, dest: Spanned, dstart:Int, dend:Int): CharSequence? {
        try
        {
            val input = Integer.parseInt(dest.toString() + source.toString())
            if (isInRange(min, max, input))
                return null
        }
        catch (nfe:NumberFormatException) {}
        return ""
    }
    private fun isInRange(a:Int, b:Int, c:Int):Boolean {
        return if (b > a) c in a..b else c in b..a
    }
}

次に、これをKotlinクラスから使用します

percentage_edit_text.filters = arrayOf(Utilities.InputFilterMinMax(1, 100))

このEditTextでは、1〜100を使用できます。

次に、これをXMLから使用します

android:inputType="number"

リターンソースを使用して私のために働く==> if(isInRange(min、max、input))リターンソース
Muzafferus

3

Edittextに最小/最大を設定する簡単な方法を作りました。私は算術キーパッドを使用しており、この方法を使用しています。

 private int limit(EditText x,int z,int limin,int limax){

    if( x.getText().toString()==null || x.getText().toString().length()==0){
        x.setText(Integer.toString(limin));
        return z=0;
    }
    else{
        z = Integer.parseInt(x.getText().toString());
         if(z <limin || z>limax){
             if(z<10){
                 x.setText(Integer.toString(limin));
                return  z=0;
             }
            else{
                x.setText(Integer.toString(limax));
                return z=limax;
            }

         }
         else
            return z = Integer.parseInt(x.getText().toString());
    }
 }

このメソッドはすべての値を受け入れますが、ユーザーの値が制限に準拠していない場合は、自動的に最小/最大制限に設定されます。例のために。limit limin = 10、limax = 80ユーザーが8を設定すると、自動的に10が変数に保存され、EditTextが10に設定されます。


3

これに対する回答はすでに100万件あり、1つは承認されています。ただし、受け入れられた回答には多数のバグがあり、残りのほとんどは、考えられるすべてのユースケースに拡張することなく、そのうちの1つ(または2つ)を修正するだけです。

したがって、私は基本的に、サポートの回答で提案されているほとんどのバグ修正をコンパイルし、範囲外の数値を0の方向(範囲が0で始まらない場合)に継続的に入力できるようにするメソッドを追加しました。それが範囲内にないことを確認してください。明確にするために、これが他の多くのソリューションで本当に問題を引き起こす唯一の時間です。

ここに修正があります:

public class InputFilterIntRange implements InputFilter, View.OnFocusChangeListener {

    private final int min, max;

    public InputFilterIntRange(int min, int max) {
        if (min > max) {
            // Input sanitation for the filter itself
            int mid = max;
            max = min;
            min = mid;
        }
        this.min = min;
        this.max = max;
    }

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

        // Determine the final string that will result from the attempted input
        String destString = dest.toString();
        String inputString = destString.substring(0, dstart) + source.toString() + destString.substring(dstart);

        // Don't prevent - sign from being entered first if min is negative
        if (inputString.equalsIgnoreCase("-") && min < 0) return null;

        try {
            int input = Integer.parseInt(inputString);
            if (mightBeInRange(input))
                return null;
        } catch (NumberFormatException nfe) {}

        return "";
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

        // Since we can't actively filter all values
        // (ex: range 25 -> 350, input "15" - could be working on typing "150"),
        // lock values to range after text loses focus
        if (!hasFocus) {
            if (v instanceof EditText) sanitizeValues((EditText) v);
        }
    }

    private boolean mightBeInRange(int value) {
        // Quick "fail"
        if (value >= 0 && value > max) return false;
        if (value >= 0 && value >= min) return true;
        if (value < 0 && value < min) return false;
        if (value < 0 && value <= max) return true;

        boolean negativeInput = value < 0;

        // If min and max have the same number of digits, we can actively filter
        if (numberOfDigits(min) == numberOfDigits(max)) {
            if (!negativeInput) {
                if (numberOfDigits(value) >= numberOfDigits(min) && value < min) return false;
            } else {
                if (numberOfDigits(value) >= numberOfDigits(max) && value > max) return false;
            }
        }

        return true;
    }

    private int numberOfDigits(int n) {
        return String.valueOf(n).replace("-", "").length();
    }

    private void sanitizeValues(EditText valueText) {
        try {
            int value = Integer.parseInt(valueText.getText().toString());
            // If value is outside the range, bring it up/down to the endpoint
            if (value < min) {
                value = min;
                valueText.setText(String.valueOf(value));
            } else if (value > max) {
                value = max;
                valueText.setText(String.valueOf(value));
            }
        } catch (NumberFormatException nfe) {
            valueText.setText("");
        }
    }

}

一部の入力ケースは「アクティブ」に処理できない(つまり、ユーザーが入力しているため)ため、ユーザーがテキストの編集を終えた後は無視して処理する必要があります。

使い方は次のとおりです。

EditText myEditText = findViewById(R.id.my_edit_text);
InputFilterIntRange rangeFilter = new InputFilterIntRange(25, 350);
myEditText.setFilters(new InputFilter[]{rangeFilter});

// Following line is only necessary if your range is like [25, 350] or [-350, -25].
// If your range has 0 as an endpoint or allows some negative AND positive numbers, 
// all cases will be handled pre-emptively.
myEditText.setOnFocusChangeListener(rangeFilter);

ここで、ユーザーが範囲の許容範囲よりも0に近い数値を入力しようとすると、次の2つのいずれかが起こります。

  1. 場合minmax同じ桁数を持って、彼らは最終桁に得れば、彼らはそれがすべてで入力することはできません。

  2. テキストがフォーカスを失ったときに範囲外の数値がフィールドに残っている場合、自動的に最も近い境界に調整されます。

もちろん、ユーザーが範囲から許可されている値よりも0から離れた値を入力することはできません。そのため、このような数値がテキストフィールドに「誤って」入力されることもありません。

既知の問題点?)

  1. これEditTextは、ユーザーが操作を終了したときにフォーカスが失われた場合にのみ機能します。

もう1つのオプションは、ユーザーが「完了」/ Returnキーを押したときにサニタイズしますが、多くの場合、またはほとんどの場合、これによりフォーカスが失われます。

ただし、ソフトキーボードを閉じても、要素のフォーカスが自動的に解除されるわけではありません。Android開発者の99.99%がそれを望んでいると思います(そして、EditText要素への焦点を絞ることは一般的には簡単なことではありませんでした)が、現時点では組み込みの機能はありません。これを回避するために私が見つけた最も簡単な方法は、必要に応じて、EditText次のようなものを拡張することです。

public class EditTextCloseEvent extends AppCompatEditText {

    public EditTextCloseEvent(Context context) {
        super(context);
    }

    public EditTextCloseEvent(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EditTextCloseEvent(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            for (InputFilter filter : this.getFilters()) {
                if (filter instanceof InputFilterIntRange)
                    ((InputFilterIntRange) filter).onFocusChange(this, false);
            }
        }
        return super.dispatchKeyEvent(event);
    }
}

これは、ビューが実際にフォーカスを失っていなくても、フィルターをだまして入力を無害化します。後でビュー自体がフォーカスを失うと、入力サニテーションが再度トリガーされますが、すでに修正されているため、何も変更されません。

閉鎖

ふew。それはたくさんありました。元々それがかなり簡単な問題であるように見えたものは、バニラAndroid(少なくともJavaでは)の多くの小さな醜い部分を明らかにしてしまいました。また、範囲に何らかの方法で0が含まれていない場合は、リスナーを追加して拡張するEditTextだけで済みます。(現実的には、範囲に0が含まれておらず、1または-1で始まる場合、問題も発生しません。)

最後の注意として、これはintに対してのみ機能します。10進数(doublefloat)で動作するように実装する方法は確かにありますが、私も元の質問者もそれを必要としないので、特に深く掘り下げたくありません。次の行とともに、完了後フィルタリングを単純に使用するのは非常に簡単です。

// Quick "fail"
if (value >= 0 && value > max) return false;
if (value >= 0 && value >= min) return true;
if (value < 0 && value < min) return false;
if (value < 0 && value <= max) return true;

intからfloat(またはdouble)に変更し、単一.(または,、国によっては?)の挿入を許可し、の代わりに10進数型の1つとして解析するだけで済みintます。

それはとにかくほとんどの仕事を処理するので、それは非常に似たように働くでしょう。


2
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        String prefix = dest.toString().substring(0, dstart);
        String insert = source.toString();
        String suffix = dest.toString().substring(dend);
        String input_string = prefix + insert + suffix;
        int input = Integer.parseInt(input_string);

        if (isInRange(min, max, input) || input_string.length() < String.valueOf(min).length())
            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;
}

2

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

1

このコードを確認してください

    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およびeditwatchfilteres with text watcherの詳細については、以下のリンクを使用してください。

http://www.mobisoftinfotech.com/blog/android/android-edittext-setfilters-example-numeric-text-field-patterns-and-length-restriction/


OPは、値が入力されているときにそれを検証したいと考えています。値が入力された後、あなたはシナリオのためのソリューションを提供している私だと思う
MysticMagicϡ

私は質問者ではありません。私はあなたの答えに疑いを持っていたので、それを明確にしました。
MysticMagicϡ

文字数をチェックしたくない。私はあなたがこのコードでカウントをチェックしようとしていると思います:if(TextUtils.isEmpty(pass)|| pass.length <[YOUR MIN LENGTH])私はユーザーが値を書き込む必要がある月の値などの値を制限するだけです1、12、13、14などではありません。つまり、12、13、14、99までは2文字の長さになります。
mertaydin 2013年

こんにちは@mertaydin私が提供したリンクを試してみましたか。その例を参照してください。あなたが入力している間、それはテキストを見ます...
itsrajesh4uguys

わかりました。私はあなたの答えと@Pratik Sharmaの答えを試します。
mertaydin 2013年

1

最大制限だけが気になる場合は、以下の行を追加してください

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 (!(number.startsWith("01")) || number.length() < 8 || number.length() >10 ) {  
.
.
.
}

最後のようなメソッドを呼び出す

   ....else if (!(Helper.isValidMobilePhone(textMobileNo))){
                        Helper.setEditTextError(etMobileNo,"Invalid Mobile Number");
                    }......

2
これは長続きではありません、つまり長さです
ポートフォリオ

1

@プラティック・シャルマ

負の数をサポートするには、filterメソッド内に次のコードを追加します。

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

}

次に、これをアクティビティから使用します。

findViewById(R.id.myEditText).setFilters(new InputFilter[]{ new InputFilterMinMax(1, 12)});

edittextを設定します:

android:inputType="number|numberSigned"

0

//まだ問題がありますが、ここでは任意の範囲(正または負)で最小、最大を使用できます

// 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 ...     
             }
         }
      }
 });

0

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());

お役に立てれば。理由なしに投票しないでください。


0

これが私が使った方法です、それは負の数のために働いています

まず、次のコードで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)});

0

これは私のコードですmax = 100、min = 0

xml

<TextView
                    android:id="@+id/txt_Mass_smallWork"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="#000"
                    android:textSize="20sp"
                    android:textStyle="bold" />

java

EditText ed = findViewById(R.id.txt_Mass_smallWork);
    ed.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {`

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(!charSequence.equals("")) {
                int massValue = Integer.parseInt(charSequence.toString());
                if (massValue > 10) {
                    ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});
                } else {
                    ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

0

これは、InputFilterを使用して行うことができます。どうやらこれは、使用できるこの入力フィルターインターフェイスだけです。入力フィルターを拡張する新しいクラスを作成する煩わしい方法を実行する前に、内部クラスインターフェイスのインスタンス化でこのショートカットを使用できます。

したがって、これを行うだけです。

EditText subTargetTime = (EditText) findViewById(R.id.my_time);
subTargetTime.setFilters( new InputFilter[] {
                new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        int t = Integer.parseInt(source.toString());
                        if(t <8) { t = 8; }
                        return t+"";

                    }
                }
        });

この例では、EditTextの値が8より大きいかどうかを確認します。そうでない場合は、8に設定する必要があります。そのため、自分で最小最大値またはフィルターロジックを考え出す必要があります。しかし、少なくともuはEditLogicに直接、非常に簡潔で短いフィルターロジックを書き込むことができます。

お役に立てれば


0

EditTextの最小値を定義するために、私はこれを使用しました:

if (message.trim().length() >= 1 && message.trim().length() <= 12) {
  // do stuf
} else {
  // Too short or too long
}

0

@Patrikのコードには素晴らしいアイデアがありますが、多くのバグがあります。@Zacと@Anthony B(負の数の解)はそれらのいくつかを解決しましたが、@ Zacのコードにはまだ3つの市長のバグがあります:

1. ユーザーがEditTextのすべてのエントリを削除した場合、再度数値を入力することはできません。もちろん、これは各フィールドでEditText変更リスナーを使用して制御できますが、各フィールドに共通のInputFilterクラスを使用することの美しさは失われますアプリのEditText。

2. @ Guernee4が言っている、たとえばmin = 3の場合、1で始まる数値を入力することは不可能です。

3. たとえばmin = 0の場合、必要なゼロを多数入力すると、エレガントな結果が得られません。または、最小値が何であっても、最初の数値の左側のサイズにカーソルを置くことができます。これは、左側に先行ゼロの束を配置します。これもエレガントではありません。

この3つのバグを解決するために、@ Zacのコードのこれらの小さな変更を考案しました。バグ#3については、左側の先行ゼロをすべて完全に削除することができませんでした。常に1にすることができますが、その場合、00、01、0100などは、000000、001、000100などよりもエレガントで有効です。等。

これがコードです:

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

            // Using @Zac's initial solution
            String lastVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend);
            String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
            int input = Integer.parseInt(newVal);

            // To avoid deleting all numbers and avoid @Guerneen4's case
            if (input < min && lastVal.equals("")) return String.valueOf(min);

            // Normal min, max check
            if (isInRange(min, max, input)) {

                // To avoid more than two leading zeros to the left
                String lastDest = dest.toString();
                String checkStr = lastDest.replaceFirst("^0+(?!$)", "");
                if (checkStr.length() < lastDest.length()) return "";

                return null;
            }
        } catch (NumberFormatException ignored) {}
        return "";
    }

ごきげんよう!


-1

ここでPratikシャルマの答えに私のテイクがためだKotlinDoubleいずれかがそれを必要とする場合

class InputFilterMinMax : InputFilter {

private var min: Double = MIN_LIMIT
private var max: Double = MIN_LIMIT

constructor(min: Int, max: Int) {
    this.min = min.toDouble()
    this.max = max.toDouble()
}

constructor(min: String, max: String) {
    this.min = min.toDouble()
    this.max = max.toDouble()
}

constructor(min: Double, max: Double) {
    this.min = min
    this.max = max
}

override fun filter(
    source: CharSequence,
    start: Int,
    end: Int,
    dest: Spanned,
    dstart: Int,
    dend: Int
): CharSequence? {
    try {
        val input = (dest.toString() + source.toString()).toDouble()
        if (isInRange(min, max, input))
            return null
    } catch (nfe: NumberFormatException) {
        Timber.e(nfe)
    }

    return ""
}

private fun isInRange(a: Double, b: Double, c: Double): Boolean {
    return if (b > a) c in a..b else c in b..a
}
}

この入力フィルターは間違っています。テキストのstart、end、dstart、dendインデックスを無視するため、途中に文字を挿入して編集テキストを変更すると、正しく機能しません
Radu
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.