Xamarin C#:尝试水平居中按钮会导致它离开屏幕
基本上,我试着用屏幕的百分比来放置一个按钮。百分比大小和百分比位置。该按钮位于X:0.5f和Y:0.0f,这意味着它应该位于屏幕顶部的中心Xamarin C#:尝试水平居中按钮会导致它离开屏幕,c#,android,xamarin,layout,center,C#,Android,Xamarin,Layout,Center,基本上,我试着用屏幕的百分比来放置一个按钮。百分比大小和百分比位置。该按钮位于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.ToInt3
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);
int MaxWidth=Resources.DisplayMetrics.WidthPixels;
int MaxHeight=Resources.DisplayMetrics.HeightPixels;
base.OnCreate(bundle);
RelativeLayout布局=新的RelativeLayout(此);
布局。设置最小高度(最大高度);
布局。设置最小宽度(最大宽度);
布局。添加视图(按钮);
SetContentView(布局);
Xamarin C#:尝试水平居中按钮会导致它离开屏幕
您可以使用来实现此功能,例如:
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);
.您在哪里将
按钮添加到布局?您的按钮的父视图是什么?请发布您的代码。@YorkShen MSFT我添加了用于添加按钮的代码。