package com.example.scrollview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import com.pb.custom.MyListView; import com.pb.custom.Utility; /** * 解决在ScrollView中嵌套ListView不能显示全部item的问题 * 方法一:重写ListView * 方法二:人工计算子控件的尺寸;调用Utility(类名,类在后面).setListViewHeightBasedOnChildren(ListView对象); * 注意:ScrollView布局下只能有一个子布局(子布局中可以嵌套其他布局,但是ScrollView下只能是一个,这个要注意),还有一个要注意的是 * 使用方法二的话每个item布局的父组件类型必须是LinearLayout
*/
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // MyListView myListView= (MyListView) findViewById(R.id.mylist); ListView myListView= (ListView) findViewById(R.id.mylist); myListView.setAdapter(new MyAdapter()); Utility.setListViewHeightBasedOnChildren(myListView); } class MyAdapter extends BaseAdapter{ @Override public int getCount() { return 25; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if(view==null) view=getLayoutInflater().inflate(R.layout.mylist_item,null); return view; } } }
package com.pb.custom; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** *重写ListView组件 * Created by dmz1024 on 2015/11/3. */ public class MyListView extends ListView { // public MyListView(Context context) { // super(context); // } public MyListView(Context context, AttributeSet attrs){ super(context, attrs); } // >>:远大于 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, mExpandSpec); } }
package com.pb.custom; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; /** * Created by dmz1024 on 2015/11/3. * 方法二:重新计算每个item高度 */ public class Utility { public static void setListViewHeightBasedOnChildren(ListView listView) { //获取ListView对应的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目 View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); //计算子项View 的宽高 totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度 } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); //listView.getDividerHeight()获取子项间分隔符占用的高度 //params.height最后得到整个ListView完整显示需要的高度 listView.setLayoutParams(params); } }
时间: 2024-10-11 05:03:34