簡體   English   中英

基於子級的ListView高度

[英]ListView Height Based on Children

我需要使用自定義ListVAdapter查找android ListView的高度。 每個ListView項目可以具有不同的高度。 我已經嘗試了以下在這里找到的代碼:

public static void setListViewHeightBasedOnChildren(ListView listView) {

    ListAdapter listAdapter = listView.getAdapter(); 
    if (listAdapter == null) {
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

但是它沒有給出實際的高度。 所有列表項的高度都相同。 是否可以找到具有不同高度的列表項的ListView高度?

您可以使用ViewTreeObserver存檔所需的效果。 將所有子項添加到列表視圖后,可以調用以下命令:

ViewTreeObserver vto = myList.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {   
        @Override
        public void onGlobalLayout() {
            int height = myList.getMeasuredHeight();  
            int width = myList.getMeasuredWidth();

                    // Do stuff with the height and width here.
        }
    }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM