2013-01-04 81 views
4

有人可以用C#解釋我這個Java代碼,因爲我使用Mono for Android?例如,我無法在Mono for Android中找到OnGlobalLayoutListener。OnGlobalLayoutListener in Mono for Android

在Android上,它看起來像這樣:

vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
@Override 
public void onGlobalLayout() { 
    int newWidth, newHeight, oldHeight, oldWidth; 

    //the new width will fit the screen 
    newWidth = metrics.widthPixels; 

    //so we can scale proportionally 
    oldHeight = iv.getDrawable().getIntrinsicHeight(); 
    oldWidth = iv.getDrawable().getIntrinsicWidth(); 
    newHeight = Math.floor((oldHeight * newWidth)/oldWidth); 
    iv.setLayoutParams(new LinearLayout.LayoutParams(newWidth, newHeight)); 
    iv.setScaleType(ImageView.ScaleType.CENTER_CROP); 

    //so this only happens once 
    iv.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
    } 
}); 

什麼是單聲道的Android相同呢?

回答

10

OnGlobalLayoutListener是一個接口,所以在C#中顯示爲ViewTreeObserver.IOnGlobalLayoutListener。由於這裏在Java中看到的C#不支持匿名類,你需要提供該接口的實現,並將其傳遞到AddOnGlobalLayoutListener()

public class MyLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener 
{ 
    public void OnGlobalLayout() 
    { 
     // do stuff here 
    } 
} 

vto.AddOnGlobalLayoutListener(new MyLayoutListener()); 

,如果你願意,你可以這樣做,但在優選的方式Android的Mono是使用事件代替偵聽器接口。在這種情況下,它暴露的GlobalLayout事件:

vto.GlobalLayout += (sender, args) => 
    { 
     // do stuff here 
    }; 

你可以得到ViewTreeObserver的一個實例是這樣的:

var contentView = activity.Window.DecorView.FindViewById(Android.Resource.Id.Content); 
contentView.ViewTreeObserver.GlobalLayout += ViewTreeObserverOnGlobalLayout; 
+3

這個工作,但是,我想事件處理程序是隻執行一次。我試圖創建一個方法處理程序,並在方法中調用事件中的 - =。這似乎並沒有阻止這名隊員的射擊。 –

+0

你能解釋一下它是什麼嗎? – Merian

+0

@Merian View樹觀察者 –

0

下面是Android開發者網站上的信息:

addOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener 聽衆)

註冊一個回調函數被調用時,全球佈局狀態或視圖中享有知名度樹變化

這裏是鏈接,你可以看看:addOnGlobalLayoutListener。這裏是onGlobalLayoutListener