How can I put a ListView into a ScrollView without it collapsing?

后端 未结 27 3324
轮回少年
轮回少年 2020-11-21 05:24

I\'ve searched around for solutions to this problem, and the only answer I can find seems to be \"don\'t put a ListView into a ScrollView\". I have yet to see any real expl

27条回答
  •  一整个雨季
    2020-11-21 05:47

    We could not use two scrolling simulteniuosly.We will have get total length of ListView and expand listview with the total height .Then we can add ListView in ScrollView directly or using LinearLayout because ScrollView have directly one child . copy setListViewHeightBasedOnChildren(lv) method in your code and expand listview then you can use listview inside scrollview. \layout xml file

    
    
     
    
            
    
                
    
                
    
                   
    
                
      
      
    
       
    

    onCreate method in Activity class:

     import java.util.ArrayList;
      import android.app.Activity;
     import android.os.Bundle;
     import android.view.Menu;
     import android.view.View;
     import android.view.ViewGroup;
     import android.widget.ArrayAdapter;
     import android.widget.ListAdapter;
      import android.widget.ListView;
    
       public class MainActivity extends Activity {
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_inside_scrollview);
        ListView list_first=(ListView) findViewById(R.id.first_listview);
        ListView list_second=(ListView) findViewById(R.id.secondList);
        ArrayList list=new ArrayList();
        for(int x=0;x<30;x++)
        {
            list.add("Item "+x);
        }
    
           ArrayAdapter adapter=new ArrayAdapter(getApplicationContext(), 
              android.R.layout.simple_list_item_1,list);               
          list_first.setAdapter(adapter);
    
         setListViewHeightBasedOnChildren(list_first);
    
          list_second.setAdapter(adapter);
    
        setListViewHeightBasedOnChildren(list_second);
       }
    
    
    
       public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // 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);
            totalHeight += listItem.getMeasuredHeight();
        }
    
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
          }
    

提交回复
热议问题