我正在做一個短信應用..其中我想驗證編輯文本(即如果用戶不會輸入電話號碼,那麼它會顯示請輸入號碼),但它沒有執行那些部分..請檢查它並給我一些建議....我的代碼是在這裏。謝謝提前..如何驗證EditText?
public class MainActivity extends Activity {
Button btnSend;
EditText txtPhoneNo;
EditText txtSMS;
String phoneNo, SMS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend=(Button) findViewById(R.id.buttonSend);
txtPhoneNo=(EditText) findViewById(R.id.editTextPhoneNo);
txtSMS=(EditText) findViewById(R.id.editTextSMS);
btnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
phoneNo=txtPhoneNo.getText().toString();
SMS=txtSMS.getText().toString();
if(phoneNo.equals(" ") || phoneNo == null) {
Toast.makeText(getBaseContext(), "Please Enter the number !", Toast.LENGTH_LONG).show();
}
else {
MyAsync ma = new MyAsync();
ma.execute();
}
}
});
}
class MyAsync extends AsyncTask<Void,Void,Void> {
ProgressDialog pd;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Wait!", "Sending...");
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, SMS, null, null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
Toast.makeText(getApplicationContext(),"Sent",Toast.LENGTH_LONG).show();
}
}
}
您可以設置edittext'android:inputType =「number」'的輸入類型。所以你只能輸入數字,而你使用'TextUtils.isEmpty(string)'來驗證。 – Raghunandan