我有三个相同的小部件。类似的内容(我省略了本例中不相关的xml元素):

<LinearLayout>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
</LinearLayout>

这迫使列表具有360度倾斜的高度。当然,这将是它的高度,即使只有很少的列表项。所以,我的问题是如何使列表具有自动高度?我想要的是ListView高度取其所有列表项总和的确切大小。

最佳答案

我以这种方式实现了它(代码正在运行,因此它更像是一个思想源而不是解决方案):

package com.customcontrols;
public class NoScrollListView extends ListView
{
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0) );

        // here I assume that height's being calculated for one-child only, seen it in ListView's source which is actually a bad idea
        int childHeight = getMeasuredHeight() - (getListPaddingTop() + getListPaddingBottom() +  getVerticalFadingEdgeLength() * 2);

        int fullHeight = getListPaddingTop() + getListPaddingBottom() + childHeight*(getCount());

        setMeasuredDimension(getMeasuredWidth(), fullHeight);
    }
}

这个计算并不完美,但它很接近,目前为止还有效。
之后,您只需创建如下布局:
卷轴视图
com.customcontrol.noscrollllistview
com.customcontrol.noscrollllistview
com.customcontrol.noscrollllistview
/滚动视图
滚动视图非常重要,因为您可以轻松地超出屏幕范围。
这个计算是由直肠驱动的,因为listview&co中的大多数计算方法都是包私有的,这对于ui的公共可继承类来说是一个非常奇怪的选择。

07-26 09:40
查看更多