Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

How to add a Label to a Relative layout and center it horizontally

$
0
0

Hi all,

I'm trying to horizontally center a label in a Relative Layout.

My intuitive way of doing it would be to add the label to the layout with an X constraint equal to the parent's width minus the label's width, all divided by two.

However, the parent's width can be had. The Label's width equals -1.

RelativeLayout relativeLayout = new RelativeLayout();

            Label CenteredLabel = new Label ();
            CenteredLabel.Text = "Center this";
            CenteredLabel.XAlign = TextAlignment.Center;
            CenteredLabel.MinimumWidthRequest = relativeLayout.Width;
            relativeLayout.Children.Add 
                (CenteredLabel, Constraint.RelativeToParent ((parent)=>
                                                {return (parent.Width-CenteredLabel.Width)/2;}),
                  Constraint.Constant(0)
                );

Can anyone suggest why this is not working? Thanks!


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>