如何在Xamarin Android中以编程方式设置Gravity

时间:2018-09-19 06:59:03

标签: xamarin xamarin.android

我想在中心放置一个线性布局。如果我给填充填充,布局正在移动,但是如果我将重力设为中心,则不行。我能知道为什么会这样以及如何实现重力。

我已附上我使用的代码。

LinearLayout outerView = new LinearLayout(context);
outerView.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
outerView.Orientation = Android.Widget.Orientation.Vertical;
//outerView.setGravity(GravityFlags.Center);
outerView.SetPadding(70,10,10,10);

1 个答案:

答案 0 :(得分:0)

First, you should change FillParent to WrapContent, so your container doesn't take all available space (if it does, then there's no point in setting the layout_gravity).

Secondly, by calling setGravity method, you're changing the way the children of given view are positioned. If you want to change how outerView is positioned in relation to it's parent, you should change it's layout_gravity. To do it, just specify the gravity when creating a LayoutParams for your outerView:

outerView.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent)
{
    Gravity = GravityFlags.Center
}

Take a look at documentation of this class: https://developer.xamarin.com/api/type/Android.Widget.LinearLayout+LayoutParams/