您的位置:首页 > 移动开发 > Android开发

Android 自定义listview适配ScrollView 自动计算高度

2016-10-27 11:45 295 查看
public class MyListView extends LinearLayout {
private BaseAdapter adapter;
private MyOnItemClickListener onItemClickListener;
boolean footerViewAttached = false;
private View footerview;

/**
* 通知更新listview
*/
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(MyListView.this,
layout, index, adapter.getItem(index));
}
}
});
ImageView imageView = new ImageView(getContext());
imageView.setLayoutParams(params);
layout.addView(v);
layout.addView(imageView);
addView(layout, index);
}
}

public MyListView(Context context) {
super(context);
initAttr(null);
}

public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
initAttr(attrs);
}

public void initAttr(AttributeSet attrs) {
setOrientation(VERTICAL);
}

/**
* 初始化footerview
*
* @param footerView
*/
public void initFooterView(final View footerView) {
this.footerview = footerView;
}

/**
* 设置footerView监听事件
*
* @param onClickListener
*/
public void setFooterViewListener(OnClickListener onClickListener) {
this.footerview.setOnClickListener(onClickListener);
}

public BaseAdapter getAdapter() {
return adapter;
}

/**
* 设置adapter并模拟listview添加????数据
*
* @param adpater
*/
public void setAdapter(BaseAdapter adpater) {
this.adapter = adpater;
removeAllViews();
if (footerViewAttached)
addView(footerview);
notifyChange();
}

/**
* 设置条目监听事件
*
* @param onClickListener
*/
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);
}
}


如果需要listview的分割线自己在item布局里直接弄好就可以了

listview的刷新要用

myListView.notifyChange();

而不是

adapter.notifyDataSetChanged();

item点击监听

myListView.setOnItemClickListener(new MyListView.MyOnItemClickListener() {
@Override
public void onItemClick(ViewGroup parent, View view, int position, Object o) {

}
});


基本功能还是和listview类似的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐