2016-12-15 73 views
0

我希望每次都能獲得佈局的高度,但現在我可以在for循環完成時獲得佈局的高度。有沒有人知道如何在for循環中每次獲得高度?getViewTreeObserver for for循環不工作,爲什麼?

for (int i = 0; i < deelnemers.size(); i++) { 

     inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View informatie = inflater.inflate(R.layout.modeldeelnemer, null); 

     TextView volgNummer = (TextView) informatie.findViewById(R.id.volgnummer); 

     volgNummer.setText("Nummer: " + deelnemers.get(i).getVolgnummer() + " /"); 
     lLayout.addView(informatie); 

     lLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
      public void onGlobalLayout() { 
       lLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); 

       int height = lLayout.getMeasuredHeight(); 
       int width = lLayout.getMeasuredWidth(); 
      } 
     }); 
    } 

回答

1

一般情況下應避免使用全局佈局偵聽器,這是不好的做法。最後,你只是想知道何時測量視圖以便鉤住該事件。我寫了一個帶有回調觀察OnMeasure調用的小布局。檢查這個佈局:MeasureCallbackLayout

當你環繞你的線性佈局佈局可以添加MeasureCallback和你想用實際大小是什麼:

measureCallbackLayout.addMeasureListener(new MeasureCallbackLayout.MeasureCallback() { 
    @Override 
    public void onMeasured() { 
     int height = lLayout.getMeasuredHeight(); 
     int width = lLayout.getMeasuredWidth(); 
    } 
});