「Android開発」EditTextで数字入力範囲の上限を判断するサンプルコード

参考コード:
private int MIN_MARK = 0;
private int MAX_MARK = 100;
//private void setRegion(EditText et)
private void setRegion( final EditText et)
{
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (start > 1)
{
if (MIN_MARK != -1 && MAX_MARK != -1)
{
int num = Integer.parseInt(s.toString());
if (num > MAX_MARK)
{
s = String.valueOf(MAX_MARK);
et.setText(s);
}
else if(num < MIN_MARK)
s = String.valueOf(MIN_MARK);
return;
}
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s)
{
if (s != null && !s.equals(“"))
{
if (MIN_MARK != -1 && MAX_MARK != -1)
{
int markVal = 0;
try
{
markVal = Integer.parseInt(s.toString());
}
catch (NumberFormatException e)
{
markVal = 0;
}
if (markVal > MAX_MARK)
{
Toast.makeText(getBaseContext(), “100以上できません", Toast.LENGTH_SHORT).show();
et.setText(String.valueOf(MAX_MARK));
}
return;
}
}
}
});
}

Android

Posted by arkgame