「Java学習」EditTextで最大入力文字数を制限する

参考コード:

public class EditTextWithLimitChar extends EditText {
private int NUM_MAX_CHAR = Integer.MAX_VALUE;
private int sum = 0; // 文字列合計
private CharSequence temp;
private int editStart;
private int editEnd;
/**
* 文字数の上限を設定
*
* @param limits
*/
public void setLimits(int limits) {
NUM_MAX_CHAR = limits;
}
public EditTextWithLimitChar(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}
public EditTextWithLimitChar(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}
public EditTextWithLimitChar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
private void init() {
addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
temp = s;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
editStart = getSelectionStart();
editEnd = getSelectionEnd();
Log.d(“TAG", “editStart=" + editStart + “, " + “editEnd="
+ editEnd);
if (temp.length() > NUM_MAX_CHAR) {
Toast.makeText(getContext(), “文字数は制限を超える",
Toast.LENGTH_SHORT).show();
s.delete(editStart – 1, editEnd);
int tempSelection = editStart;
setText(s);
setSelection(tempSelection);
}
}
});
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}

Java

Posted by arkgame