如何在 Xamarin 中删除 ViewTreeObserver? [英] How to remove ViewTreeObserver in Xamarin?
问题描述
假设我需要获取并设置视图的高度.在 Android 中,众所周知,只有在绘制后才能获得视图高度.如果您使用的是 Java,则有很多答案,其中最广为人知的方法之一如下所示,取自 this answer一个>:
Let's just say I need to get and set a View's height. In Android, it's known you can get a view height only after it's drawn. If you're using Java, many answers, one of the most well-known way is like this one below, taken from this answer:
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
view.getHeight(); //height is ready
}
});
因此我搜索 C#/Xamarin 版本,并发现此方法有效:
Thus I search C#/Xamarin version, and found this works:
int viewHeight = 0;
ViewTreeObserver vto = view.ViewTreeObserver;
vto.GlobalLayout += (sender, args) =>
{
viewHeight = view.Height;
};
事情是,它一次又一次地开火.在 Java 版本中,它可以删除view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
Thing is, it fired again and again. In Java version, it can be removed with
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
如何在 C#\Xamarin 中实现?我是否应该使用 boolean
属性来知道它是否被执行?有没有办法像android那样做?
How to do it in C#\Xamarin? Should I resort to using boolean
properties to know whether it's executed or not? Is there not way to do it like the android one?
推荐答案
如果您正在使用 C# 事件,如果您需要取消订阅,请避免使用匿名事件,或者您可以实现 IOnGlobalLayoutListener
并添加/移除监听器:
If you are using C# Events, avoid using anonymous events if you need to unsubscribe, or you can implement the IOnGlobalLayoutListener
and add/remove the listener:
为要调用的事件创建一个 EventHandler
方法:
Create an EventHandler
method for the event to invoke:
void Globallayout_handler(object sender, EventArgs e)
{
// ViewTreeObserver.IOnGlobalLayoutListener events
}
订阅:
var viewTreeObserver = aView.ViewTreeObserver;
viewTreeObserver.GlobalLayout += Globallayout_handler;
取消订阅:
var viewTreeObserver = aView.ViewTreeObserver;
viewTreeObserver.GlobalLayout -= Globallayout_handler;
C# 中的 Java 侦听器样式:
添加并实现ViewTreeObserver.IOnGlobalLayoutListener
:
public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer,
ViewTreeObserver.IOnGlobalLayoutListener
{
~~~~
public void OnGlobalLayout()
{
// ViewTreeObserver.IOnGlobalLayoutListener events
}
}
现在您可以使用 Java 方式添加和删除此侦听器:
Now you can use the Java way to add and remove this listener:
aView.ViewTreeObserver.RemoveOnGlobalLayoutListener(this);
aView.ViewTreeObserver.AddOnGlobalLayoutListener(this);
这篇关于如何在 Xamarin 中删除 ViewTreeObserver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!