在 Xamarin.Forms 中添加方向更改布局

Sud*_*dha 5 c# android ios xamarin.forms

我需要实现的是,在将屏幕从纵向更改为横向时向现有页面添加布局。我设法使用void OnSizeAllocated(double width, double height)检测方向变化。但我无法在此事件上添加布局。

我的示例 C# 代码是

   public class MyLayoutView : ContentPage
   {
      StackLayout portraitcontent = null;
      StackLayout landscapecontent = null;
      StackLayout footer = null;

   public MyLayoutView ()
    {

    portraitcontent = new StackLayout ();
    landscapecontent = new StackLayout ();
    footer = new StackLayout ();

    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
    this.BackgroundColor = Color.FromHex ("#ffffff");
    this.Content = new StackLayout
        {
            Children =
            {
                portraitcontent ,
                landscapecontent ,
                footer 
            }
            };
         }
   }
Run Code Online (Sandbox Code Playgroud)

OnSizeAllocated 方法

   protected override void OnSizeAllocated(double width, double height)
    {
        base.OnSizeAllocated(width, height);

        if (width < height) {
            // In Portrait
            portraitcontent .IsVisible = true;
            landscapecontent.IsVisible = false;
            Debug.WriteLine ("Application Is in portrait");
        } else {
            // In Landscape
            portraitcontent .IsVisible = false;
            landscapecontent.IsVisible = true;

            landscapecontent.Children.Clear ();

            Label LandscapeLabel= new Label
            {
              Text = "<Each Time Text Changes>",
              HorizontalOptions = LayoutOptions.StartAndExpand,
              TextColor=Xamarin.Forms.Color.FromHex("#000000")
            };

            landscapecontent.Children.Add(LandscapeLabel); 

            Debug.WriteLine ("Application Is in Landscape");
        }
    }
Run Code Online (Sandbox Code Playgroud)

当重入被阻止时,它抛出无法修改集合的错误。每次当方向改变时,我都需要在 stacklayout 中添加一个新标签。我怎样才能以适当的方式实现它?

提前致谢

小智 5

重写 OnSizeAllocation 可能不是最好的方法。我只是将它放入我的代码中,从纵向到横向调用此方法大约 25 次。

我正在尝试的另一件事是在表单页面上挂钩事件处理程序:

this.SizeChanged += (sender, e) => setOrientation(this);    // Connect Orientation Switcher
Run Code Online (Sandbox Code Playgroud)

为了跟踪真实的页面旋转并避免处理器不必要的工作,我创建了一个类变量来存储当前状态,然后将其添加到高度/宽度比较中。

void setOrientation (Page p)
     if ( isPortrait && (p.Width > p.Height) ) { do stuff }
     if ( !isPortrait && (p.Width < p.Height) ) { do stuff }
Run Code Online (Sandbox Code Playgroud)

这更快,但目前似乎存在内存泄漏,一些布局来回切换。仍在努力。无法相信,随着移动设备已经有屏幕旋转多年,开发工具将可用,但没有简单的方法来做到这一点。似乎它们可以让我们将几种不同的布局连接到一个页面,并让运行时根据环境自动选择。我不是开发人员,也许这比我想象的要困难得多。

如果我能轮换工作,我会尽力记住回来并发布代码。


Fem*_*jin 3

当方向改变时,分配的大小会被多次调用。我认为你必须做更多的验证,比如检查孩子的数量,以避免视图重复。

    if(landscapecontent.Children.Count>1)
     { 
       //Don't add any views
     }
Run Code Online (Sandbox Code Playgroud)

只要我尝试过,就没有用于旋转的事件处理程序。这是一种在代码中进行黑客攻击,以在方向改变时改变视图。

即使您可以在这里使用已接受的答案..希望它能满足您的目的..