キーが入力されるたびに、このメソッドを使用します。
public static int getIndex(String input) {
return input.replaceAll("_", "").length();
}
public static String prepareOutput(String actual, String input) {
input = input.replaceAll("_", "");
int diff = actual.length() - input.length();
if (diff < 0) {
return input;
}
for (int i = 0; i < diff; i++) {
input += "_";
}
return input;
}
このような:
final EditText ed = (EditText) findViewById(R.id.editText1);
ed.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
String input = s.toString();
String output = prepareOutput("This is a question", input);
if (output.compareTo(input) != 0) {
ed.setText(output);
ed.setSelection(getIndex(output));
}
}
});