2013-08-02 23 views
5

目前我有幾個視圖,屏幕被劃分爲兩個部分addOnGlobalLayoutListener和onWindowFocusChanged之間的區別?

實施例:

text1  image1 

text2 

text3 

text4 

問題是,如果圖像1高,它就會重疊上左側的TextView的,所以我用在左邊強制textview寬度不超過imageview的左邊。

android:layout_toLeftOf="@id/imageView1" 

但是,每個textview都與imageview的左側對齊,因爲我不知道它的高度,直到創建視圖。我希望所有textview低於imageview的基線,刪除android:layout_toLeftOf的佈局規則

因此,我搜索解決方案並找到兩種方法?

1.onWindowFocusChanged 

2.getViewTreeObserver().addOnGlobalLayoutListener 

兩者都可以獲得視圖的yaxis。

的問題是:

1. what is the difference between them ? 

2. I tried approach 2 , but it is not working, how to fix it? 

代碼:

 image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      ImgY = image.getY(); 
     } 
    }); 

    lng.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      if (lng.getY() > ImgY) { 
       lng.removeRule(RelativeLayout.LEFT_OF); 
      } 
     } 
    }); 

的錯誤是我想設置一個全球性的值來存儲的ImageView的y,但它警告The final local variable ImgY cannot be assigned, since it is defined in an enclosing type此外,removeRule功能返回

The method removeRule(int) is undefined for the type TextView 

非常感謝您的幫助。

回答

0

您可以使用帶有文本的內嵌圖像,代替TextView而不是該方法。看看this