计算一个列表视图的大小或如何告诉它完全展开视图、大小、列表

2023-09-12 01:31:05 作者:你算哪块草莓夹心小饼干

我目前正在使用一个ListView滚动型的内部。我知道,从我读过,这是看不起,但我试图让ListView控件,以通过显示其所有的行,所以没有必要为它滚动完全展开。我一直在挣扎,但是,与如何告诉ListView的完全展开以显示所有的行,因为它需要一个定义的高度。有谁知道一个方法来计算一个完全展开的ListView的高度,在绘制之前?

I am currently trying to use a ListView inside of a ScrollView. I know from what I've read that this is looked down upon, but I'm trying to get the ListView to expand completely by showing all of its rows so there is no need for it to scroll. I've been struggling, however, with how to tell the ListView to completely expand to show all of its rows since it needs a defined height. Does anyone know of a way to calculate the height of a fully expanded ListView before it is drawn?

这个问题主要源于你不能把一个滚动视图中的另一个滚动视图里面的事实。我没关系的事实,ListView控件不能作为长期滚动,我可以把它展开显示所有的行。 ,我不能这样做,但没有能够给它一个定义的高度,这看来我需要计算。

This problem mainly stems from the fact that you can't put a scrollable view inside of another scrollable view. I am okay with the fact that the ListView won't be able to scroll as long as I can make it expand to show all of its rows. I cannot do this, however, without being able to give it a defined height, which it seems I would need to calculate.

请参阅以下链接的草图(我是一个新的用户,所以我不能发布一个)。这表明我的完整布局太大了物理的屏幕,并且需要以显示在底部列表和按钮的其余部分滚动。我试图传达的虚拟的屏幕太大,无法在一个屏幕上,即使没有在ListView那里。

See the url below for a sketch (I'm a new user so I'm not allowed to post one). It shows that my full layout is too big for the "physical" screen and needs to scroll in order to show the rest of the list and buttons at the bottom. I'm trying to get across that the "virtual" screen is too big to fit on one screen even without the ListView there.

http://img51.imageshack.us/img51/7210/screenmockup.png

推荐答案

好了,多亏了鲁迪,他的建议是非常有益的。下面是它如何实现。

Well, thanks to Rudy, his suggestions was very helpful. Here is how it can be implemented.

1)创建扩展的ListView一个新的类:

1) Create a new class that extends ListView:

package com.example.android.views;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ListView;

public class ExpandedListView extends ListView {

    private android.view.ViewGroup.LayoutParams params;
    private int old_count = 0;

    public ExpandedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getCount() != old_count) {
            old_count = getCount();
            params = getLayoutParams();
            params.height = getCount() * (old_count > 0 ? getChildAt(0).getHeight() : 0);
            setLayoutParams(params);
        }

        super.onDraw(canvas);
    }

}

2),...,最后是新的视图添加到您的XML布局文件:

2) ... and finally add the new view to your xml layout file:

<com.example.android.views.ExpandedListView
    android:id="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="none"
    android:padding="0px"
    />