欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-02-07 15:35:07
本文介绍了android的listview点击item使item展开的做法的实现代码,分享给大家,具体如下: 效果图: 原理是点击item的时候,重新measure...

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

效果图:

android的ListView点击item使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

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