ScrollView嵌套listview,并计算listview的高度

来源:互联网 发布:张国荣但愿人长久知乎 编辑:程序博客网 时间:2024/05/29 15:44

1:首先是布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ScrollView        android:id="@+id/sc"        android:layout_width="match_parent"        android:layout_height="wrap_content">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content">            <ListView                android:id="@+id/lv"                android:layout_width="match_parent"                android:layout_height="match_parent"></ListView>        </LinearLayout>    </ScrollView></LinearLayout>
2:接下来就是代码了

public class MainActivity extends AppCompatActivity {    private ListView lv;    private ScrollView sc;    private List<String> list=new ArrayList<>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        lv= (ListView) findViewById(R.id.lv);        sc= (ScrollView) findViewById(R.id.sc);        for (int i=0;i<20;i++){            list.add("条目:"+i);        }        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);        lv.setAdapter(adapter);        //调用方法        setListViewHeightBasedOnChildren(lv);    }    public void setListViewHeightBasedOnChildren(ListView listView) {        ListAdapter listAdapter = lv.getAdapter();        if (listAdapter == null) {            // pre-condition            return;        }        int totalHeight = 0;        // listAdapter.getCount()返回数据项的数目        for (int i = 0; i < listAdapter.getCount(); i++) {            View listItem = listAdapter.getView(i, null, lv);            // 计算子项View 的宽高            listItem.measure(0, 0);            // 统计所有子项的总高度            totalHeight += listItem.getMeasuredHeight();        }        ViewGroup.LayoutParams params = lv.getLayoutParams();        // listView.getDividerHeight()获取子项间分隔符占用的高度        // params.height最后得到整个ListView完整显示需要的高度        params.height = totalHeight + (lv.getDividerHeight() * (listAdapter.getCount() - 1));        lv.setLayoutParams(params);    }}

0 0