Android IP地址验证

IP格式为四个三位数;且数字输入有严格限制。所以就要用到正则表达式判断。
MainActivity.java

public class MainActivity extends Activity {
private EditText et1,et2,et3,et4;
private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(getWindow().FEATURE_NO_TITLE);//隐藏标题栏
        setContentView(R.layout.main);
        et1=(EditText) findViewById(R.id.editText1);
        et2=(EditText) findViewById(R.id.editText2);
        et3=(EditText) findViewById(R.id.editText3);
        et4=(EditText) findViewById(R.id.editText4);
        btn=(Button) findViewById(R.id.button1);
    }
public void onClick(View v) {
/*分别获取输入值*/
    String string1=et1.getText().toString().trim();
    String string2=et2.getText().toString().trim();
    String string3=et3.getText().toString().trim();
    String string4=et4.getText().toString().trim();

    /*整合输入值*/
    String string = string1 + "." + string2 + "." + string3 + "."
            + string4;

/*正则表达式*/
    String ip = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|[1-9])\\."
            + "(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d{2}|\\d)\\."
            + "(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d{2}|\\d)\\."
            + "(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d{2}|\\d)";//限定输入格式

    Pattern p = Pattern.compile(ip);
    Matcher m = p.matcher(string);
    boolean b=m.matches();
    if(string1.equals("")||string2.equals("")||string3.equals("")||string4.equals("")){
        Toast.makeText(this, "IP地址不可为空!", Toast.LENGTH_LONG).show();
    }
    else{
    if(b==false){
        Toast.makeText(this, "IP格式输入错误", Toast.LENGTH_LONG).show();
    }
    else{
    /*传值跳转*/
    Intent intent = new Intent(MainActivity.this, IP.class);  

    intent.putExtra("ip", string);
    startActivity(intent);
    }
    }
}
}

IP.java

public class IP extends Activity {
    private TextView textView1;
@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.number);
    textView1=(TextView) findViewById(R.id.text1);

    Intent intent=getIntent();
    String s=intent.getStringExtra("ip");//接收输入的值
    textView1.setText("IP为:"+s+"");//重写textView,显示输入值
}

}

Android IP地址验证_第1张图片 Android IP地址验证_第2张图片

你可能感兴趣的:(Android IP地址验证)