ScrollView中只能放一个控件,一般都放LinearLayout,orientation属性值为vertical。在LinearLayout中放需要呈现的内容。ListView也在其中,ListView的高度设为适应自身内容(wrap_content)。但是为啥在scrollview中嵌套listview会出现只显示第一条listitem的高度呢,原因是:scrollview的ontach方法的滚动事件消费处理,ListView控件的高度设定问题
从谷歌那里找到的ScrollView嵌套ListView只显示一行的解决办法相信很多人都遇到过,然后大部分都是用这位博主的办法解决的吧
刚开始我也是用这个办法解决的,首先感谢这位哥的大私奉献,贴上地址
http://blog.csdn.net/p106786860/article/details/10461015
2、解决的核心代码
- public void setListViewHeightBasedOnChildren(ListView listView) {
- // 获取ListView对应的Adapter
- ListAdapter listAdapter = listView.getAdapter();
- if (listAdapter == null) {
- return;
- }
- int totalHeight = 0;
- for (int i = 0, len = listAdapter.getCount(); i
> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
public void notifyChange() {
int count = getChildCount();
if (footerViewAttached) {
count--;
}
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
for (int i = count; i < adapter.getCount(); i++) {
final int index = i;
final LinearLayout layout = new LinearLayout(getContext());
layout.setLayoutParams(params);
layout.setOrientation(VERTICAL);
View v = adapter.getView(i, null, null);
v.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(MyListView2.this,
layout, index, adapter.getItem(index));
}
}
});
ImageView imageView = new ImageView(getContext());
imageView.setLayoutParams(params);
layout.addView(v);
layout.addView(imageView);
addView(layout, index);
}
}
public MyListView2(Context context) {
super(context);
initAttr(null);
}
public MyListView2(Context context, AttributeSet attrs) {
super(context, attrs);
initAttr(attrs);
}
public void initAttr(AttributeSet attrs) {
setOrientation(VERTICAL);
}
public void initFooterView(final View footerView) {
this.footerview = footerView;
}
public void setFooterViewListener(OnClickListener onClickListener) {
this.footerview.setOnClickListener(onClickListener);
}
public BaseAdapter getAdapter() {
return adapter;
}
public void setAdapter(BaseAdapter adpater) {
this.adapter = adpater;
removeAllViews();
if (footerViewAttached)
addView(footerview);
notifyChange();
}
public void setOnItemClickListener(MyOnItemClickListener onClickListener) {
this.onItemClickListener = onClickListener;
}
public void noMorePages() {
if (footerview != null && footerViewAttached) {
removeView(footerview);
footerViewAttached = false;
}
}
public void mayHaveMorePages() {
if (!footerViewAttached && footerview != null) {
addView(footerview);
footerViewAttached = true;
}
}
public static interface MyOnItemClickListener {
public void onItemClick(ViewGroup parent, View view, int position,
Object o);
}
}
这个adapter就是你获取数据后设置的,也就是上面两点的综合
关注
打赏
