Xamarin C#:尝试水平居中按钮会导致它离开屏幕

Xamarin C#: Trying to center button horizontally causes it to go off screen

基本上,我正在尝试使用屏幕百分比放置按钮。百分比大小和百分比位置。按钮位于 X: 0.5f 和 Y: 0.0f 意味着它应该位于屏幕顶部的中央。

Button button = new Button(Application.Context);
int height = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.HeightPixels * heightPercent);
int width = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.WidthPixels * widthPercent);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent)
{
    LeftMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.WidthPixels * xPercent - (width / 2)),
    TopMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.HeightPixels * yPercent),
    BottomMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.HeightPixels * yPercent) + height,
    RightMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.WidthPixels * xPercent + (width / 2)),
    Width = width,
    Height = height
};


button.Tag = buttonID;
button.LayoutParameters = params1;

上面的代码导致按钮离开屏幕,尽管这没有任何意义。如果我将页边距更改为此;

LeftMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.WidthPixels * xPercent),
TopMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.HeightPixels * yPercent),
BottomMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.HeightPixels * yPercent) + height,
RightMargin = Convert.ToInt32(Application.Context.Resources.DisplayMetrics.WidthPixels * xPercent) + width,

该按钮将出现在屏幕上,但会稍微向右偏移。我试图将它向左移动一半大小,但我不知道为什么布局会出错。有什么提示吗?

如何将按钮添加到布局:

int MaxWidth = Resources.DisplayMetrics.WidthPixels;
int MaxHeight = Resources.DisplayMetrics.HeightPixels;

base.OnCreate(bundle);
RelativeLayout layout = new RelativeLayout(this);

layout.SetMinimumHeight(MaxHeight);
layout.SetMinimumWidth(MaxWidth);

<BUTTON GETS CREATED HERE>

layout.AddView(button);
SetContentView(layout);

Xamarin C#: Trying to center button horizontally causes it to go off screen

您可以使用 LayoutRules.CenterHorizontal 来实现此功能,例如:

RelativeLayout layout = new RelativeLayout(this);
Button button = new Button(this);
button.Text = "Center Button";

RelativeLayout.LayoutParams parametros = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
parametros.AddRule(LayoutRules.CenterHorizontal);
layout.AddView(button, parametros);

SetContentView(layout);

Effect.