在某些特殊场合,要求输入大写字母。我们可以对输入的EditText进行设置,不管用户输入大写或者小写字母,都自动转换为大写。
代码很简单,示例如下:
package com.example.upperandlowertransform;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ReplacementTransformationMethod;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText etInput = (EditText) findViewById(R.id.etInput);
//限制只输入大写字母的地方,小写自动转换为大写
etInput.setTransformationMethod(new InputCapLowerToUpper());
}
class InputCapLowerToUpper extends ReplacementTransformationMethod{
@Override
protected char[] getOriginal() {
char[] lower = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
return lower;
}
@Override
protected char[] getReplacement() {
char[] upper = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
return upper;
}
}
}
大写转换为小写也可以类似的来实现。