728x90
반응형
우선 EditText에 숫자만 입력되도록 레이아웃 xml의 EditText에 다음속성을 선언합니다.
** android:inputType="number"
아래와 같은 class를 만들어 줍니다.
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")});
Reference : Is there a way to define a min and max value for EditText in Android? <Stack OverFlow>
728x90
반응형
'Android > Code Piece' 카테고리의 다른 글
Color hex 코드를 R, G, B 값으로 분리하기 (0) | 2020.07.18 |
---|---|
ScrollView에 잔상이 남는 현상 (0) | 2020.05.04 |
RecyclerView의 스크롤 차단하기 (0) | 2020.04.23 |
Stroke의 색상을 동적으로 바꾸기 (0) | 2020.04.23 |
비트맵 이미지를 원형으로 크롭하기 (0) | 2020.04.11 |
댓글