在项目中,我们常常会遇到一个ScrollView里面会嵌套ListView的情况,但往往你会发现,ListView和ScrollView的滚动时间会有冲突问题,造成ListView不能完全显示。虽然网上有给出解决方案,但事实上并不好用,并不完美。
public void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); 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);
}
因此,为了彻底解决问题,就需要我们另辟途径了,我们使用 LinearLayout 绑定 Adapter的方法来代替ListView
将 adapter 里面的 view 全部加入 LinearLayout 并设置回调监听
public class LinearLayoutForListView extends LinearLayout { private BaseAdapter adapter; private OnItemClickListener mOnItemClickListener; public OnItemClickListener getOnItemClickListener() { return mOnItemClickListener; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } public LinearLayoutForListView(Context context) { super(context); } public LinearLayoutForListView(Context context, AttributeSet attrs) { super(context, attrs); } public LinearLayoutForListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setAdapter(BaseAdapter adapter) { this.adapter = adapter; // setAdapter 时添加 view bindLinearLayout(); } /** * 绑定布局 */ public void bindLinearLayout() { if (adapter == null) { return; } int count = adapter.getCount(); this.removeAllViews(); for (int i = 0; i < count; i++) { final View v = adapter.getView(i, null, null); final int tmp = i; final Object obj = adapter.getItem(i); // view 点击事件触发时回调我们自己的接口 v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClicked(v, obj, tmp); } } }); addView(v); } } /** * * 回调接口 */ public interface OnItemClickListener { /** * @param v 点击的 view * @param obj 点击的 view 所绑定的对象 * @param position 点击位置的 index */ public void onItemClicked(View v, Object obj, int position); }} 调用
list.setAdapter(madapter);list.setOnItemClickListener(new LinearLayoutForListView.OnItemClickListener() { @Override public void onItemClicked(View v, Object obj, int position) { }});