? ? ? ?在項(xiàng)目中經(jīng)常會用到ScrollView嵌套ListView的情況堤器。如果使用原生的ListView會出現(xiàn)只顯示一行的情況,出現(xiàn)這個的原因是在scrollView中ListView在OnMeasure階段無法測出實(shí)際的高度。
1墩虹、第一種方法
????我們需要給他設(shè)置AT_MOST模式以支持很大的高度反惕。這時候可以自定義一個MyListView 繼承自Listview,然后重寫onMeasure方法即可:
/**
* Created by tangzejian on 2018/3/27.
* ScrollView嵌套ListView
*/
public class ScrollViewListViewextends ListView {
public ScrollViewListView(Context context) {
super(context);
? ? }
public ScrollViewListView(Context context, AttributeSet attrs) {
super(context, attrs);
? ? }
public ScrollViewListView(Context context, AttributeSet attrs,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int defStyle) {
super(context, attrs, defStyle);
? ? }
/**
* 重寫該方法稻励,達(dá)到使ListView適應(yīng)ScrollView的效果
*/
? ? @Override
? ? protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >>2,
? ? ? ? ? ? ? ? MeasureSpec.AT_MOST);
? ? ? ? super.onMeasure(widthMeasureSpec, expandSpec);
? ? }
}
2、第二種方法
????動態(tài)設(shè)置ListView的高度:
public void setListViewHeightBasedOnChildren(ListView listView) {
// 獲取ListView對應(yīng)的Adapter
? ? ListAdapter listAdapter = listView.getAdapter();
? ? if (listAdapter ==null) {
return;
? ? }
int totalHeight =0;
? ? for (int i =0, len = listAdapter.getCount(); i < len; i++) {
// listAdapter.getCount()返回數(shù)據(jù)項(xiàng)的數(shù)目
? ? ? ? View listItem = listAdapter.getView(i, null, listView);
? ? ? ? // 計算子項(xiàng)View 的寬高
? ? ? ? listItem.measure(0, 0);
? ? ? ? // 統(tǒng)計所有子項(xiàng)的總高度
? ? ? ? totalHeight += listItem.getMeasuredHeight();
? ? }
ViewGroup.LayoutParams params = listView.getLayoutParams();
? ? params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -1));
? ? // listView.getDividerHeight()獲取子項(xiàng)間分隔符占用的高度
// params.height最后得到整個ListView完整顯示需要的高度
? ? listView.setLayoutParams(params);
}
以上兩種方法都可以解決ListView的Item顯示不全問題。
ps:如果使用第一種方法還會遇到一個小問題問題望抽,ListView加載完后ScroyView或滑動到ListView的位置加矛,這時候可以自定義一個MyScroyView 繼承自ScroyView,然后重寫computeScrollDeltaToGetChildRectOnScreen方法即可:
/**
* Created by tangzejian on 2018/4/11.
* 禁止加載數(shù)據(jù)時滑到底部
*/
public class MyScrollViewextends ScrollView {
public MyScrollView(Context context) {
super(context);
? ? }
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
? ? }
public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
? ? }
/**
? ? * @param rect 解決
? ? * @return 由于子控件的大小導(dǎo)致ScrollView滾動到底部的問題
*/
? ? @Override
? ? protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
return 0;
? ? }
}