我想在我的 Xamarin Forms 项目中使用步进器,但它不会在 Android 中正确调整宽度。当我设置边距时,WithRequest 根本不起作用,它只调整两个按钮中的一个按钮的大小,另一个按钮仍然是正常大小。
按钮的大小不是根据WidthRequest
属性设置的。如果要设置按钮的大小,则必须制作自己的步进控制。
对StepperRenderer方法的源代码进行一些更改,OnElementChange
使其适用于您自己的自定义控件。以下是修改后的版本StepperRenderer
:
[assembly:ExportRenderer(typeof(MyStepper),typeof(MyStepperRenderer))]
namespace StepperDemo.Droid
{
public class MyStepperRenderer : ViewRenderer<Stepper, LinearLayout>
{
AButton _downButton;
AButton _upButton;
public MyStepperRenderer()
{
AutoPackage = false;
}
protected override LinearLayout CreateNativeControl()
{
return new LinearLayout(Context) {
Orientation = Orientation.Horizontal
};
}
protected override void OnElementChanged(ElementChangedEventArgs<Stepper> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
_downButton = new AButton(Context) { Text = "-", Gravity = GravityFlags.Center, Tag = this };
//Set the MinWidth of Button
_downButton.SetMinWidth(50);
_downButton.SetOnClickListener(StepperListener.Instance);
_upButton = new AButton(Context) { Text = "+", Tag = this };
_upButton.SetOnClickListener(StepperListener.Instance);
//Set the MinWidth of Button
_upButton.SetMinWidth(50);
if (e.NewElement != null)
{
//Set the Width and Height of the button according to the WidthRequest
_downButton.LayoutParameters = new LayoutParams((int)e.NewElement.WidthRequest, LayoutParams.MatchParent);
_upButton.LayoutParameters = new LayoutParams((int)e.NewElement.WidthRequest, LayoutParams.MatchParent);
}
var layout = CreateNativeControl();
layout.AddView(_downButton);
layout.AddView(_upButton);
SetNativeControl(layout);
}
UpdateButtonEnabled();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
switch (e.PropertyName)
{
case "Minimum":
UpdateButtonEnabled();
break;
case "Maximum":
UpdateButtonEnabled();
break;
case "Value":
UpdateButtonEnabled();
break;
case "IsEnabled":
UpdateButtonEnabled();
break;
}
}
void UpdateButtonEnabled()
{
Stepper view = Element;
_upButton.Enabled = view.IsEnabled ? view.Value < view.Maximum : view.IsEnabled;
_downButton.Enabled = view.IsEnabled ? view.Value > view.Minimum : view.IsEnabled;
}
class StepperListener : Java.Lang.Object, IOnClickListener
{
public static readonly StepperListener Instance = new StepperListener();
public void OnClick(global::Android.Views.View v)
{
var renderer = v.Tag as MyStepperRenderer;
if (renderer == null)
return;
Stepper stepper = renderer.Element;
if (stepper == null)
return;
if (v == renderer._upButton)
((IElementController)stepper).SetValueFromRenderer(Stepper.ValueProperty, stepper.Value + stepper.Increment);
else if (v == renderer._downButton)
((IElementController)stepper).SetValueFromRenderer(Stepper.ValueProperty, stepper.Value - stepper.Increment);
}
}
}
然后你可以根据CustomRenderer Tutorial使用这个渲染器。
步进按钮的宽度会正确改变: