for循环中的getViewTreeObserver无法正常工作,为什么?

时间:2016-12-15 14:57:33

标签: android

我希望每次都能获得布局的高度,但是现在我在完成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 个答案:

答案 0 :(得分:2)

一般来说,避免使用不好的全局布局监听器。最后,您只想知道何时测量视图,以便挂钩该事件。我写了一个带有回调的小布局来观察OnMeasure调用。检查此布局:MeasureCallbackLayout

当您围绕线性布局包裹该布局时,您可以添加MeasureCallback并使用实际大小执行您想要的操作:

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