Display ListView in ScrollView in Android

Source: Internet
Author: User

In the previous project, we encountered such a requirement that a ListView should be nested in an external ScrollView. After trying, we found that the height of the ListView had a problem and only showed one point at a time, there are also problems with slide. By default, Android prohibits the escaping of ListView in ScrollView. Although this design is not highly respected, it finds a solution on Stackoverflow, that is, after setting the Adapter for the ListView, re-calculate the height of the sub-item, and then re-set the height for the ListView through LayoutParams, so that the display will be normal. Of course, the above issues do not exist in iOS development. iOS allows you to add a View in the View, so iOS can add another UITableView in a UIScrollView. Go back to the question and see how to solve this problem in Android development. It is very easy to call the following static method after setting the adapter for ListView: [java] public class Utility {public static void setListViewHeightBasedOnChildren (ListView listView) {ListAdapter listAdapter = listView. getAdapter (); if (listAdapter = null) {www.2cto.com // pre-condition return;} int totalHeight = 0; for (int I = 0; I <listAdapter. getCount (); I ++) {View listItem = listAdapter. getView (I, null, listView); listItem. measure (0, 0); www.2cto.com totalHeight + = listItem. getMeasuredHeight ();} ViewGroup. layoutParams params = listView. getLayoutParams (); params. height = totalHeight + (listView. getDividerHeight () * (listAdapter. getCount ()-1); listView. setLayoutParams (params );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.