问题
Does any one know how to make a field required in Xamarin/Android app?
I have this field and button in my Android Layout, and I'd like to make sure the info is entered before they go to the next activity.
<TextView
android:text="Zip Code:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/zipCodeLabel"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="@+id/btnSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btnSearch"
android:textSize="30sp" />
If found this for iOS, but can't find something similar for Android: https://developer.xamarin.com/recipes/ios/standard_controls/text_field/validate_input/
回答1:
There are a number of ways to validate input depending upon what your user experience requirements are.
android:digits to restrict input:
<EditText
android:id="@+id/zipCodeEntry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="1234567890-"
/>
Validate after entry done and show error message:
button.Click += delegate {
if (!ValidateZipCode(zipCodeEntry.Text))
{
zipCodeEntry.Error = "Enter Valid USA Zip Code";
return;
}
DoSubmit();
protected bool ValidateZipCode(string zipCode)
{
string pattern = @"^\d{5}(\-\d{4})?$";
var regex = new Regex(pattern);
Log.Debug("V", regex.IsMatch(zipCode).ToString());
return regex.IsMatch(zipCode);
}
Implement View.IOnKeyListener on your Activity and check/validate every key entry
zipCodeEntry.SetFilters(new IInputFilter[] { this });
public bool OnKey(View view, [GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if (view.Id == Resource.Id.zipCodeEntry)
{
Log.Debug("V", keyCode.ToString()); // Validate key by key
}
return false;
}
Use an InputFilter (Implement IInputFilter on your activity):
public ICharSequence FilterFormatted(ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++)
{
if ((Character.IsDigit(source.CharAt(i)) || source.CharAt(i) == '-'))
sb.Append(source.CharAt(i));
}
return (sb.Length() == (end - start)) ? null : new Java.Lang.String(sb.ToString());
}
来源:https://stackoverflow.com/questions/38484055/how-to-validated-fields-in-an-xamarin-android-app