Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

android - Disable scrolling of a ListView contained within a ScrollView

I want to show a Profile screen for my users.

It must have three views (2 Buttons and a ImageView) and a ListView to show the content made by that user.

However, I don't want the ListView to scroll. Instead, I want it to be as big as needed, and to put all my views inside a ScrollView, so the three first views scroll out with the ListView. This, of course, does not work as intended.

All my three items are inside a LinearLayout. I thought of making them the first item in the ListView, but this leads to them being selectable as the first item, and having to do some unneeded coding.

Is there a way to do this the easy way or will I have to stick with making the Layout the first item in my ListView?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found a very simple solution for this. Just get the adapter of the listview and calculate its size when all items are shown. The advantage is that this solution also works inside a ScrollView.

Example:

public static void justifyListViewHeightBasedOnChildren (ListView listView) {

    ListAdapter adapter = listView.getAdapter();

    if (adapter == null) {
        return;
    }
    ViewGroup vg = listView;
    int totalHeight = 0;
    for (int i = 0; i < adapter.getCount(); i++) {
        View listItem = adapter.getView(i, null, vg);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

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

Call this function passing over your ListView object:

justifyListViewHeightBasedOnChildren(myListview);

The function shown above is a modidication of a post in: Disable scrolling in listview

Please note to call this function after you have set the adapter to the listview. If the size of entries in the adapter has changed, you need to call this function as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...