本文介绍了android的ListView点击item使item展开的做法的实现代码,分享给大家,具体如下:
效果图:
原理是点击item的时候,重新measure list的各个item的高度
代码语言:javascript复制list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<? parent, View view, int position, long id) {
MyData data = myList.get(position);
if (oldPostion == position) {
if (data.expand) {
oldPostion = -1;
}
data.expand = !data.expand;
}else{
oldPostion = position;
data.expand = true;
}
int totalHeight = 0;
for(int i=0;i<myAdapter.getCount();i ) {
View viewItem = myAdapter.getView(i, null, list);
viewItem.measure(0, 0);
totalHeight = viewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = list.getLayoutParams();
params.height = totalHeight
(list.getDividerHeight() * (list.getCount() - 1));
list.setLayoutParams(params);
myAdapter.notifyDataSetChanged();
}
});
adapter:
代码语言:javascript复制private class myAdapter extends BaseAdapter{
@Override
public int getCount() {
return myList.size();
}
@Override
public Object getItem(int position) {
return myList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyTag tag = new MyTag();
MyData data = myList.get(position);
if(convertView == null) {
convertView = inflater.inflate(R.layout.expand_item_layout, null);
tag.item1 = (TextView)convertView.findViewById(R.id.item1);
tag.item2 = (RelativeLayout)convertView.findViewById(R.id.item2);
convertView.setTag(tag);
}else{
tag = (MyTag)convertView.getTag();
}
if(data.expand) {
tag.item2.setVisibility(View.VISIBLE);
}else{
tag.item2.setVisibility(View.GONE);
}
tag.item1.setText(data.name);
return convertView;
}
}
private class MyTag{
private TextView item1;
private RelativeLayout item2;
}
private class MyData{
boolean expand;
String name;
}
代码在https://github.com/nickgao1986/StepSport
以上就是本文的全部内容,希望对大家的学习有所帮助。