ScrollView中嵌入ListView只显示一条的解决办法
通常情况下我们不会在ScrollView中嵌套ListView,但是如果面试官非让我嵌套的话也是可以的。
在ScrollView添加一个ListView会导致listview控件显示不全,通常只会显示一条,究竟是什么原因呢?
两个控件的滚动事件冲突导致。所以需要通过listview中的item数量去计算listview的显示高度,从而使其完整展示,如下提供一个方法供大家参考。
解决办法如下所示:
lv=(ListView)findViewById(R.id.lv);
adapter=newMyAdapter();
lv.setAdapter(adapter);setListViewHeightBasedOnChildren(lv);
---------------------------------------------------
publicvoidsetListViewHeightBasedOnChildren(ListViewlistView){
ListAdapterlistAdapter=listView.getAdapter();
if(listAdapter==null){
return;
}
inttotalHeight=0;
for(inti=0;i<listAdapter.getCount();i++)
{ViewlistItem=listAdapter.getView(i,null,listView);
listItem.measure(0,0);
totalHeight+=listItem.getMeasuredHeight();
}
ViewGroup.LayoutParamsparams=listView.getLayoutParams();
params.height=totalHeight+(listView.getDividerHeight()*(listAdapter.getCount()-1));
params.height+=5;
listView.setLayoutParams(params);}
现阶段最好的处理的方式是:自定义ListView,重载onMeasure()方法,设置全部显示。
importandroid.widget.ListView;
/****@Description:scrollview中内嵌listview的简单实现
**@File:ScrollViewWithListView.java
***@Version*/
publicclassScrollViewWithListViewextendsListView{
publicScrollViewWithListView(android.content.Contextcontext,android.util.AttributeSetattrs){super(context,attrs);}
/**
*Integer.MAX_VALUE>>2,如果不设置,系统默认设置是显示两条*/
publicvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
intexpandSpec=MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec,expandSpec);
}
}
以上内容是小编给大家介绍的ScrollView中嵌入ListView只显示一条的解决办法,希望对大家有所帮助!