【问题标题】:Xamarin.Android, How to unsubscribe from View Tree Observer inXamarin.Android,如何取消订阅 View Tree Observer
【发布时间】:2017-07-05 13:43:21
【问题描述】:

我有一个像这样的视图树观察器:

rowsContainerVto = rowsContainerView.ViewTreeObserver;
rowsContainerVto.GlobalLayout += RowsContainerVto_GlobalLayout;

void RowsContainerVto_GlobalLayout (object sender, EventArgs e)
{
    if(rowsContainerVto.IsAlive)
        rowsContainerVto.GlobalLayout -= RowsContainerVto_GlobalLayout;

    vW = rowsContainerView.Width;
    Console.WriteLine ("\r now width is " + vW);
}

它应该做的是在视图布局后找到宽度,它做得很好。我只是不知道如何阻止它一遍又一遍地运行。

以上基本上是基于提出的建议。这只会使应用程序崩溃。当我摆脱“IsAlive”时,循环将永远继续。在第一次绘制和布局后,我似乎无法找到阻止它的方法。

【问题讨论】:

    标签: c# android xamarin native android-viewtreeobserver


    【解决方案1】:

    由于您的 EventHandler 是匿名的,因此您无法再次取消订阅它,因为您没有对它的引用。

    如果您想保持在同一范围内,可以执行以下操作:

    EventHandler onGlobalLayout = null;
    onGlobalLayout = (sender, args) =>
    {
        rowsContainerVto.GlobalLayout -= onGlobalLayout;
        realWidth = rowsContainerView.Width;
    }
    rowsContainerVto.GlobalLayout += onGlobalLayout;
    

    或者,您可以将 EventHandler 作为方法:

    private void OnGlobalLayout(sender s, EventArgs e)
    {
        rowsContainerVto.GlobalLayout -= OnGlobalLayout;
        realWidth = rowsContainerView.Width;
    }
    
    rowsContainerVto.GlobalLayout -= OnGlobalLayout;
    

    这只是意味着rowsContainerVtorealWidth 必须是类成员变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2012-03-14
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多