Listview和其他滑动控件嵌套使用的坑

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24349695/article/details/76073440

RecyclerView和ListView

异同比较:

相同点:都可以实现垂直方向的滚动列表效果;都需要使用适配器(Adapter)
不同点:ListView只能实现垂直滚动列表,但RecyclerView还可以实现水平、多列、跨列等复杂的滚动列表;RecyclerView不但需要Adapter,还必须有LayoutManager,用法更复杂一些。
总结:ListView能做到的,RecyclerView都能做到,反之则不行。RecyclerView用法比ListView复杂。
一般用法:

ListView用法
ListView listView = (ListView) findViewById(R.id.list_view);listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
RecyclerView用法
recyclerView = findView(R.id.id_recyclerview);
//设置布局管理器
recyclerView.setLayoutManager(layout);
//设置adapter
recyclerView.setAdapter(adapter) ;
//设置Item增加、移除动画
recyclerView.setItemAnimator(new DefaultItemAnimator());
//添加分割线
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL_LIST));

RecyclerView的点击事件要自己手动去写

Scrollview和Listview
当Scrollview中添加了Listview时会导致页面无法显示在最上面,还有listview会显示不全
解决方式:
首先固定listview的长度,其次解决无法置顶的问题,找一个控件,使得控件聚焦,如下面3行代码。
mViewPaper.setFocusable(true);
mViewPaper.setFocusableInTouchMode(true);
mViewPaper.requestFocus();
ScrollView中嵌套ListView时显示不全的解决方案

1、动态获取listview的高度

在ScrollView中嵌套ListView时,ListView只能显示一行多一点.
经过验证,简单有效,在listview.setAdapter()之后调用Utility.setListViewHeightBasedOnChilren(listview)就Okay 了。
ublic 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);
}


2、重写listview(重点是onMeasure方法

public class MyListView extends ListView {

public MyListView(Context context) {
// TODO Auto-generated method stub
super(context);
}

public MyListView(Context context, AttributeSet attrs) {
// TODO Auto-generated method stub
super(context, attrs);
}

public MyListView(Context context, AttributeSet attrs, int defStyle) {
// TODO Auto-generated method stub
super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}




猜你喜欢

转载自blog.csdn.net/qq_24349695/article/details/76073440