Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android edittext minmum and maximum value

I am in development of an android app.. actually i need to set a minimum and maximum value for an editext entry my minimum value is 18 and maximum is 65.I did the exact code of this

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

I got this code fro this site only ... Is there a way to define a min and max value for EditText in Android? actually this for values between 1 and 12 and for that value it is working fine but when i changed for my value 18 and 45 it is not working ... can anyone please help me.. what change i have to be done for this ...

like image 964
user2223317 Avatar asked Oct 21 '22 09:10

user2223317


1 Answers

You should replace the line:

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

With

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

Look at Can someone help me with the parameters to the Android InputFilter "filter" method? (plus regex) to understand why

like image 96
EyalBellisha Avatar answered Oct 24 '22 03:10

EyalBellisha