Xamarin C#:尝试水平居中按钮使其离开屏幕

问题描述 投票:0回答:1

基本上我正在尝试使用百分比的屏幕放置一个按钮。百分比大小和百分比位置。按钮位于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);
c# android xamarin layout center
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.