gowtham T
gowtham T

Reputation: 53

How to change the position or size of a view in Relative Layout at runtime in xamarin.forms

What I did is I have added a label to a relative layout by setting all constraint.

Below is my code for that.

relativeLayout.Children.Add(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Width * 0.55;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Y;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Width * .45;
    }), Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
    {
        return sibling.Height;
    }));

and it working perfectly.

Now I want to change that label(textLabel) X Constraint and Width Constraint dynamically. For example, from the above code X Constraint is sibling.Width * 0.55 and width is sibling.Width * .45, then need to change to X as sibling.Width * 0.55 + 10 and width is sibling.Width * .45 - 50. How to do that?

My guess is that it can be done by removing the label for the relative Layout and added again to relative layout with new constraint. But I think there will be a better solution for this.

Upvotes: 1

Views: 854

Answers (1)

gowtham T
gowtham T

Reputation: 53

As @LeoZhu-MSFT comment, it works perfectly for me. Here is how I fixed the problem

For my question,

Now I want to change that label(textLabel) X Constraint and Width Constraint dynamically. For example, from the above code X Constraint is sibling.Width * 0.55 and width is sibling.Width * .45, then need to change to X as sibling.Width * 0.55 + 10 and width is sibling.Width * .45 - 50. How to do that?

To Change X Constraint

 RelativeLayout.SetXConstraint(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
 {
    return sibling.Width * 0.55 + 10;
 }));

To Change Width Constraint

 RelativeLayout.SetWidthConstraint(textLabel, Constraint.RelativeToView(innerBorderBox, (parent, sibling) =>
 {
    return sibling.Width * .45 - 50;
 }));

For more details on

RelativeLayout.SetWidthConstraint => https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.relativelayout.setwidthconstraint?view=xamarin-forms RelativeLayout.SetXConstraint => https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.relativelayout.setxconstraint?view=xamarin-forms

Upvotes: 2

Related Questions