- scrollview 与listview 一起使用时,listview 的高度无法自适应解决方法如下:
编写自定义组件:MyListView:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
在布局文件引用
<com.android.medo.compoment.MyListView
android:id="@+id/project_chart_lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="0dip"
android:divider="#00000000">
</com.android.medo.compoment.MyListView>
计算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);
}
生成适配展示数据后,调用setListViewHeightBasedOnChildren(ListView listView)
presenter.setListViewHeightBasedOnChildren(mBinding.projectChartLv);
此时解决了listview在scrollview 的自适应高度问题。
- 页面加载显示scrollview页面,无法置顶显示数据,而是直接显示listview的问题.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusableInTouchMode="true"> //只需设置该属性未true即可
<ScrollView
android:scrollbars="none"
android:id="@+id/sv_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.android.medo.compoment.MyListView
android:dividerHeight="0dip"
android:divider="#00000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/project_chart_lv">
</com.android.medo.compoment.MyListView>
</LinearLayout>
</ScrollView>
</LinearLayout>
设置scrollview的父级标签focusableInTouchMode=”true”