在 Xamarin.Forms 中,我过去只需使用自定义渲染器即可使用 Xamarin.Forms.Platform.Android 中的选择器,如此处所述。该网站展示了如何删除选择器的边框,但也展示了两种可能的选择器。
这就是 AppCompat 中的选择器的样子(我已经从该网站提取了图像)。这也是 MAUI 中的默认设置:
这就是我想要达到的结果:
但是,在 MAUI 中,使用 CompatibilityRenderer 或 Handler,或者甚至尝试更改 styles.xml 文件,我似乎无法让第二个选择器工作。 PickerRenderer 作为 CompatibilityRenderer 只是 AppCompat 的一个,也是处理程序。
我已经找到了这个问题的解决方案(回答了我的问题here,但我对其进行了一些修改以更好地适应我的情况)。通过使用自定义处理程序,可以在 MAUI 中创建旧的选择器,如下所示:
首先创建一个自定义选择器
public class CustomPicker : Picker
然后在 Platforms/Android/Handlers 中制作自定义处理程序:
public class CustomPickerHandler : ViewHandler<CustomPicker, EditText>
然后在处理程序中,像这样创建选择器:
protected override View CreatePlatformView()
{
var edit = new EditText(MainActivity.Instance);
// Set the placeholder
edit.Hint = VirtualView.Title;
// Disable selection, cursor, etc
edit.SetCursorVisible(false);
edit.Focusable = false;
edit.FocusableInTouchMode = false;
edit.Click += (s, e) =>
{
var p = this.VirtualView as CustomPicker;
var items = p.Items;
var n = new NumberPicker(MainActivity.Instance);
n.MinValue = 0;
n.MaxValue = items.Count - 1;
// Set this to true if looping is required
n.WrapSelectorWheel = false;
// If there is a value already selected, select it
var lastSelectedIndex = p.SelectedIndex != -1 ? p.SelectedIndex : 0;
n.Value = lastSelectedIndex;
n.SetDisplayedValues(items.ToArray<string>());
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.Instance);
var dlg = alertDialog
.SetTitle(p.Title)
.SetView(n)
.SetPositiveButton("OK", (s, e) =>
{
p.SelectedIndex = n.value
edit.Text = p.Items[n.Value].ToString(); // Assign the selected value to EditText
})
.Create();
dlg.Show();
};
return edit;
}
最后,在 MauiProgram.cs 中注册选择器处理程序:
#IF ANDROID
builder.ConfigureMauiHandlers(collection =>
{
collection.AddHandler(typeof(CustomPicker), typeof(CustomPickerHandler))
}
#ENDIF