我是Android新手,所以请原谅我的简单问题。
我正在尝试制作一个包含 3 个简单字段的注册表:全名、电子邮件和电话号码。
我需要做两件简单的事情:
1)我希望当用户结束写入字段时出现错误警报(editText.setError(errMsg))。例如,当用户点击以下字段时,如果上一个字段中存在错误,则会显示错误警报。应该在哪里插入函数?目前,我正在将它写在函数 public void afterTextChanged(Editable s) 中,但它在用户键入时显示警报错误并继续显示,直到他写的内容符合检查。
2)如果用户在某个字段上犯了错误并成功纠正了它,我想用一个积极的图标(如绿色的选中图标)显示该字段,这意味着他的更正被接受。
我正在使用 onFocusChange(),但它对我不起作用。我做错了什么?
请在下面找到我的代码,非常感谢您的宝贵帮助。
public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
// private static final String PHONE_REGEX = "\d{3}-\d{7}";
// private static final String PHONE_REGEX = "(\d{3})-(\d{3})-(\d{4})";
private static final String PHONE_REGEX = "([0-9-( )]+)";
// Error Messages
private static final String REQUIRED_MSG = "Invalid name. You have to input at least 3 characters";
private static final String EMAIL_MSG = "Invalid email";
private static final String PHONE_MSG = "Invalid number";
// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}
// call this method when you need to check phone number validation
public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
/*
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
String text = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
// text required and editText is blank, so return false
if ( required && !hasText(editText) ) return false;
// pattern doesn't match so returning false
if (required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
if ( required && !hasNumber(editText)) return false;
return true;
}
*/
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean bRequired) {
// text required and editText is blank, so return false
String sText = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
if (sText.length() == 0) {
if (bRequired) {
editText.setError("*Field required");
return false;
}
} else {
// filled field
// pattern doesn’t match so returning false
if (!Pattern.matches(regex, sText)) {
editText.setError(errMsg);
return false;
}
}
return true;
}
// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length less that 3 means there is no text
if (text.length() <= 3) {
editText.setError(REQUIRED_MSG);
return false;
}
return true;
}
public static boolean hasNumber(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length less that 6 and more than 11 means not available
if (text.length() <= 6 && text.length() >= 11) {
editText.setError(PHONE_MSG);
return false;
}
return true;
}
}//Validation
public class ConTct extends Activity implements OnClickListener, OnTouchListener, OnFocusChangeListener{
Button mButton;
EditText mFullName, mEmail, mDialZone, mPhone;
static WebView mWebView;
static ProgressBar mProgressBar;
EditText mBrokerId, mIP, mAreaPhonePrefix, mLastName, mPassWord, mCampaign, mSubCampaign, mCountryID, mCity, mAdress, mIsDemo;
public static final String myURL = "http://iphoneapp.optionrally.com:5757";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.contct);
registerViews();
mDialZone=(EditText)findViewById(R.id.countryPhonePrefix);
mWebView=(WebView)findViewById(R.id.myWebView);
mWebView.setVerticalScrollBarEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TheWebViewClient());
mWebView.loadUrl("http://media-dispatcher.com/tds/mobile/?mdaf=FormInApp");
mProgressBar=(ProgressBar)findViewById(R.id.myProgressBar);
GetCountryZipCode();
setUpInvisibleFields();
getIpAdressFromDevice();
// getUserCountry(getApplicationContext());
GetCountryIDCode();
//Get a Tracker (should auto-report)
((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
}//oncreate()
public void setUpInvisibleFields(){
mBrokerId=(EditText)findViewById(R.id.brokerId);
mIP=(EditText)findViewById(R.id.ip);
mAreaPhonePrefix=(EditText)findViewById(R.id.areaPhonePrefix);
mLastName=(EditText)findViewById(R.id.lastName);
mPassWord=(EditText)findViewById(R.id.password);
mCampaign=(EditText)findViewById(R.id.campaign);
mSubCampaign=(EditText)findViewById(R.id.subCampaign);
mCountryID=(EditText)findViewById(R.id.countryId);
mCity=(EditText)findViewById(R.id.city);
mAdress=(EditText)findViewById(R.id.address);
mIsDemo=(EditText)findViewById(R.id.isDemo);
}//setUpInvisibleFields
private void registerViews() {
mFullName = (EditText) findViewById(R.id.firstName);
mFullName.setFocusableInTouchMode(true);
mFullName.requestFocus();
// TextWatcher would let us check validation error on the fly
mFullName.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.hasText(mFullName);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
mEmail = (EditText) findViewById(R.id.email);
mEmail.setFocusableInTouchMode(true);
mEmail.requestFocus();
mEmail.addTextChangedListener(new TextWatcher() {
// after every change has been made to this editText, we would like to check validity
public void afterTextChanged(Editable s) {
Validation.isEmailAddress(mEmail, true);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
mPhone = (EditText) findViewById(R.id.phoneNumber);
mPhone.setFocusableInTouchMode(true);
mPhone.requestFocus();
mPhone.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Validation.isPhoneNumber(mPhone, true);
Validation.hasText(mPhone);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
mButton = (Button) findViewById(R.id.SubmitRegisterButton);
mButton.setOnClickListener(this);
}
private void submitForm() {
// Submit your form here. your form is valid
Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
}
private boolean checkValidation() {
boolean ret = true;
if (!Validation.hasText(mFullName)){
ret = false;
}
if (!Validation.isEmailAddress(mEmail, true)){
ret = false;
}
if (!Validation.isPhoneNumber(mPhone, true)){
ret = false;
}
if (!Validation.hasText(mPhone)){
mFullName.requestFocus();
ret = false;
}
return ret;
}//checkValidation
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
if(checkValidation()==true){
mFullName.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
mPhone.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ( checkValidation () ){
submitForm();
Intent i = new Intent(getApplicationContext(), ThanksZuser.class);
startActivity(i);
finish();
//send to our crm
grabURL(myURL);
}else
Toast.makeText(ConTct.this, "Form contains error", Toast.LENGTH_LONG).show();
}
private static class TheWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
mProgressBar.setVisibility(View.GONE);
}
}//MyWebViewClient
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Get an Analytics tracker to report app starts & uncaught exceptions etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}//onStart()
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//Stop the analytics tracking
GoogleAnalytics.getInstance(this).reportActivityStop(this);
sendDatatoGAfromOnStop();
}//onStop()
public void sendDatatoGAfromOnStop(){
String name = mFullName.getText().toString();
name=name.replace("@", "|");
name=name.replace(".", "!");
String email = mEmail.getText().toString();
email=email.replace("@", "|");
email=email.replace(".", "!");
String phone = mPhone.getText().toString();
phone=phone.replace("@", "|");
phone=phone.replace(".", "!");
Tracker t = ((AppManager) getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("Ostp// " + name)
.setAction(email)
.setLabel(phone)
.build());
}
public void sendDatatoGAfromOnTouch(){
String name = mFullName.getText().toString();
name=name.replace("@", "|");
name=name.replace(".", "!");
String email = mEmail.getText().toString();
email=email.replace("@", "|");
email=email.replace(".", "!");
String phone = mPhone.getText().toString();
phone=phone.replace("@", "|");
phone=phone.replace(".", "!");
Tracker t = ((AppManager) getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory("Otch// " + name)
.setAction(email)
.setLabel(phone)
.build());
}
// validating phone
private boolean isValidPhoneNumber(String phone2) {
boolean check;
if(phone2.length() < 6 || phone2.length() > 13){
check = false;
}else{
check = true;
}
return check;
}
// validating email
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating full name
private boolean isValidFullName(String pass) {
if (pass != null && pass.length() > 2) {
return true;
}
return false;
}
public boolean Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
String valid_name;
if (edt.getText().toString().length() <= 2) {
edt.setError("Invalid name. You have to input at least 3 characters");
valid_name = null;
return false;
} else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
return false;
} else {
valid_name = edt.getText().toString();
return true;
}
}
public String GetCountryZipCode(){
String CountryID="";
String CountryZipCode="";
TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
CountryID= manager.getSimCountryIso().toUpperCase();
String[] rl=this.getResources().getStringArray(R.array.CountryCodes);
for(int i=0;i<rl.length;i++){
String[] g=rl[i].split(",");
if(g[1].trim().equals(CountryID.trim())){
CountryZipCode=g[0];
break;
}
}
mDialZone.setText( "+ " + CountryZipCode);
return CountryZipCode;
}//GetCountryZipCode
public String GetCountryIDCode(){
String CountryID="";
String CountryIDCode="";
TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//getNetworkCountryIso
CountryID= manager.getSimCountryIso().toUpperCase();
String[] rl=this.getResources().getStringArray(R.array.CountryIDCodes);
for(int i=0;i<rl.length;i++){
String[] g=rl[i].split(",");
if(g[1].trim().equals(CountryID.trim())){
CountryIDCode=g[0];
break;
}
}
mCountryID.setText(CountryIDCode);
return CountryIDCode;
}//GetCountryZipCode
//if the user touched the submit, button, send the data to ga
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
/*
if (GeneralValidation()==true){
sendDatatoGAfromOnTouch();
}
*/
sendDatatoGAfromOnTouch();
} else {
}
return false;
}//onTouch
//SEND DATA TO CRM
class myHttpPost extends AsyncTask<String, Void, String> implements HttpUriRequest{
public myHttpPost() {
super();
// TODO Auto-generated constructor stub
}
public myHttpPost(String url) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
BufferedReader inBuffer = null;
String result = "fail";
String url = myURL;
// Create a new HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
String l_ID, l_BrokerId, l_IP, l_SubBrokerID, l_AreaPhonePrefix, l_additionalPrefix, l_LastName, l_PassWord, l_terms, l_isLead, l_skinId, l_Campaign, l_languageId, l_SubCampaign, l_CountryID, l_City, l_Adress, l_IsDemo, l_birthday;
l_ID = "1010";
l_BrokerId ="4";
l_SubBrokerID="4";
l_IP=mIP.getText().toString();
l_AreaPhonePrefix= "972";
l_LastName= "my last name";
l_PassWord="my password";
l_languageId="2";
l_terms="on";
l_Campaign="1824";
l_SubCampaign="InsideApp";
l_additionalPrefix="03";
l_CountryID= mCountryID.getText().toString();
l_City = " my city";
l_Adress= " my adress";
l_IsDemo="0";
l_birthday="1900-01-01 00:00";
l_isLead = "yes";
l_skinId="2";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<req>");
stringBuilder.append(PrepareXmlItem("id", l_ID));
stringBuilder.append(PrepareXmlItem("brokerId", l_BrokerId));
stringBuilder.append(PrepareXmlItem("ip", l_IP));
stringBuilder.append(PrepareXmlItem("subBrokerId", l_SubBrokerID));
stringBuilder.append("<msg>");
stringBuilder.append(PrepareXmlItem("areaPhonePrefix", l_AreaPhonePrefix));
stringBuilder.append(PrepareXmlItem("lastName", l_LastName));
stringBuilder.append(PrepareXmlItem("password", l_PassWord));
stringBuilder.append(PrepareXmlItem("campaign", l_Campaign));
stringBuilder.append(PrepareXmlItem("subCampaign", l_SubCampaign));
stringBuilder.append(PrepareXmlItem("additionalPrefix", l_additionalPrefix));
stringBuilder.append(PrepareXmlItem("countryId", l_CountryID));
stringBuilder.append(PrepareXmlItem("city", l_City));
stringBuilder.append(PrepareXmlItem("address", l_Adress));
stringBuilder.append(PrepareXmlItem("languageId", l_languageId));
stringBuilder.append(PrepareXmlItem("isDemo", l_IsDemo));
stringBuilder.append(PrepareXmlItem("birthday", l_birthday));
stringBuilder.append(PrepareXmlItem("terms", l_terms));
stringBuilder.append(PrepareXmlItem("isLead", l_isLead));
stringBuilder.append(PrepareXmlItem("skinId", l_skinId));
stringBuilder.append(PrepareXmlItem("mobilePrefix", mDialZone.getText().toString()));
stringBuilder.append(PrepareXmlItem("mobileNumber", mPhone.getText().toString()));
stringBuilder.append(PrepareXmlItem("firstName", mFullName.getText().toString()));
stringBuilder.append(PrepareXmlItem("email", mEmail.getText().toString()));
stringBuilder.append("</msg>");
stringBuilder.append("</req>");
try {
StringEntity se = new StringEntity(stringBuilder.toString());
se.setContentType("text/xml");
httppost.setEntity(se);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Execute HTTP Post Request
try {
HttpResponse response = httpclient.execute(httppost);
System.out.println("we are sending data " + response.toString());
result="got it";
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
try {
throw new Exception(response.getStatusLine().getReasonPhrase());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage();
}finally{
if (inBuffer != null) {
try {
inBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
@Override
public RequestLine getRequestLine() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addHeader(Header header) {
// TODO Auto-generated method stub
}
@Override
public void addHeader(String name, String value) {
// TODO Auto-generated method stub
}
@Override
public boolean containsHeader(String name) {
// TODO Auto-generated method stub
return false;
}
@Override
public Header[] getAllHeaders() {
// TODO Auto-generated method stub
return null;
}
@Override
public Header getFirstHeader(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Header[] getHeaders(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Header getLastHeader(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public HttpParams getParams() {
// TODO Auto-generated method stub
return null;
}
@Override
public ProtocolVersion getProtocolVersion() {
// TODO Auto-generated method stub
return null;
}
@Override
public HeaderIterator headerIterator() {
// TODO Auto-generated method stub
return null;
}
@Override
public HeaderIterator headerIterator(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void removeHeader(Header header) {
// TODO Auto-generated method stub
}
@Override
public void removeHeaders(String name) {
// TODO Auto-generated method stub
}
@Override
public void setHeader(Header header) {
// TODO Auto-generated method stub
}
@Override
public void setHeader(String name, String value) {
// TODO Auto-generated method stub
}
@Override
public void setHeaders(Header[] headers) {
// TODO Auto-generated method stub
}
@Override
public void setParams(HttpParams params) {
// TODO Auto-generated method stub
}
@Override
public void abort() throws UnsupportedOperationException {
// TODO Auto-generated method stub
}
@Override
public String getMethod() {
// TODO Auto-generated method stub
return null;
}
@Override
public URI getURI() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isAborted() {
// TODO Auto-generated method stub
return false;
}
}
private String PrepareXmlItem(String tag, String val){
return "<" + tag + ">" + val + "</" + tag + ">";
}
public void grabURL(String url){
new myHttpPost().execute(myURL);
}
public String getIpAdressFromDevice(){
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
mIP.setText(ip);
return ip;
}
public String intToIp(int i) {
return ((i >> 24 ) & 0xFF ) + "." +
((i >> 16 ) & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
( i & 0xFF) ;
}
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
* @param context Context reference to get the TelephonyManager instance from
* @return country code or null
*/
public String getUserCountry(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
}
else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
mCountryID.setText(networkCountry);
return networkCountry.toLowerCase(Locale.US);
}
}
}
catch (Exception e) { }
return null;
}
}//ConTct.class
想尝试EditText.clearFocus()
函数。在分配编辑文本后调用它创建可能会有所帮助。
问题也可能出在您的XML文件中,因此请分享。
将<requestFocus/>
添加到您的编辑文本中也可能有所帮助。
例如:
<EditText
android:layout_width="wrap_content"
android:layout_height=wrap_content"
<requestFocus />
</EditText>