我正在尝试使用自定义edittext让用户输入IP地址。它只允许最多255和3个周期的值,并且它在纵向上工作正常但在横向视图中显示软键盘时,只显示其中一个周期。在任一方向正确输入IP地址,并且在横向移除键盘后,edittext正确显示IP地址。
有什么想法吗?我希望用户在输入时看到IP地址,而不仅仅是键盘被移除时。
public class IPAddressKeyListener extends NumberKeyListener {
private char[] mAccepted;
private static IPAddressKeyListener sInstance;
@Override
protected char[] getAcceptedChars() {
return mAccepted;
}
private static final char[] CHARACTERS =
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
private IPAddressKeyListener() {
mAccepted = CHARACTERS;
}
public static IPAddressKeyListener getInstance() {
if (sInstance != null) return sInstance;
sInstance = new IPAddressKeyListener();
return sInstance;
}
/**
* Display a number-only soft keyboard.
*/
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart,int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i=0; i<splits.length; i++) {
if (Integer.parseInt(splits[i]) > 255){
return "";
}
}
}
}
return null;
}
测试活动
public class MainActivity extends Activity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edAddress = (EditText) findViewById(R.id.IPAddress);
edAddress.setKeyListener(IPAddressKeyListener.getInstance());
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btn.setText(edAddress.getText());
}
});
}
布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/IPAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/IPAddress"
android:layout_below="@+id/IPAddress"
android:text="IPAddress" />