首页 > 系统 > Android > 正文

android的ListView点击item使item展开的做法的实现代码

2019-10-21 21:34:00
字体:
来源:转载
供稿:网友

本文介绍了androidListView点击item使item展开的做法的实现代码,分享给大家,具体如下:

效果图:

android,ListView,点击,item

原理是点击item的时候,重新measure list的各个item的高度

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:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表