gpt4 book ai didi

android - 如何验证 Xamarin/Android 应用程序中的字段

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:59 24 4
gpt4 key购买 nike

有谁知道如何在 Xamarin/Android 应用程序中创建必填字段?

我的 Android 布局中有这个字段和按钮,我想确保在他们进入下一个 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" />

如果找到适用于 iOS 的内容,但找不到适用于 Android 的类似内容: https://developer.xamarin.com/recipes/ios/standard_controls/text_field/validate_input/

最佳答案

根据您的用户体验要求,有多种验证输入的方法。

android:digits 限制输入:

<EditText
android:id="@+id/zipCodeEntry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="1234567890-"
/>

输入完成后验证并显示错误信息:

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);
}

enter image description here

在您的Activity 上实现View.IOnKeyListener 并检查/验证每个键输入

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;
}

使用 InputFilter(在您的 Activity 中实现 IInputFilter):

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());
}

关于android - 如何验证 Xamarin/Android 应用程序中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38484055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com