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

Posted

技术标签:

【中文标题】Xamarin C#:试图水平居中按钮会导致它离开屏幕【英文标题】:Xamarin C#: Trying to center button horizontally causes it to go off screen 【发布时间】:2018-06-12 17:19:54 【问题描述】:

基本上我正在尝试使用屏幕百分比放置按钮。百分比大小和百分比位置。按钮放置在 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);

【问题讨论】:

您在哪里将Button 添加到您的布局中?你的Button 的父视图是什么?请发布您的代码。 @YorkShen-MSFT 我添加了用于添加按钮的代码。 【参考方案1】:

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

您可以使用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.

【讨论】:

以上是关于Xamarin C#:试图水平居中按钮会导致它离开屏幕的主要内容,如果未能解决你的问题,请参考以下文章

Stack View 导致 Swift 3.0 中带有图像的按钮离开屏幕

Xamarin.Forms 图像缩放挑战

ViewDidAppear 导致我的标签消失(Xamarin.ios,C#)

如何将四个按钮水平和垂直居中?

我如何垂直和水平居中所有这些元素?

Facebook发送按钮导致水平滚动