ListView中嵌套ListView

    xiaoxiao2024-11-29  3

    ListView中嵌套ListView,就是在父ListView的Item中有ListView。和平常的设置适配器是一样的。但是这么做,子ListView只显示一项。要解决将子ListView全部显示出来的问题,只需要重新计算一下其大小。 具体实现:继承ListView,重写OnMeasure方法。这样只需要在xml文件中使用这个自定义的ListView就可以了 先看效果图

    自定义ListView的代码:

    public class NoScrollListView extends ListView { public NoScrollListView(Context context) { super(context); } public NoScrollListView(Context context, AttributeSet attrs) { super(context, attrs); } public NoScrollListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }

    父ListView的适配器:

    class AllOrderAdapter extends BaseAdapter{ private LayoutInflater inflater; AllOrderAdapter(LayoutInflater inflater){ this.inflater=inflater; } @Override public int getCount() { return 3; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { AllOrderParentHolder holder=null; if(convertView==null){ holder=new AllOrderParentHolder(); convertView=inflater.inflate(R.layout.all_order_parent_item,null); holder.listView= (NoScrollListView) convertView.findViewById(R.id.listview_all_order_parent); convertView.setTag(holder); } else{ holder= (AllOrderParentHolder) convertView.getTag(); } holder.listView.setAdapter(new AllOrderChildAdapter(inflater)); holder.listView.addHeaderView(inflater.inflate(R.layout.all_order_header,null)); return convertView; } } class AllOrderParentHolder{ NoScrollListView listView; }

    子ListView的适配器

    class AllOrderChildAdapter extends BaseAdapter{ private LayoutInflater inflater; AllOrderChildAdapter(LayoutInflater inflater){ this.inflater=inflater; } @Override public int getCount() { return 2; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { AllOrderChildHolder holder=null; if(convertView==null){ holder=new AllOrderChildHolder(); convertView=inflater.inflate(R.layout.all_order_child_item,null); holder.icon= (ImageView) convertView.findViewById(R.id.iv_icon); holder.goodsName= (TextView) convertView.findViewById(R.id.tv_goods_name); holder.price= (TextView) convertView.findViewById(R.id.tv_price); holder.num= (TextView) convertView.findViewById(R.id.tv_value); convertView.setTag(holder); } else { holder= (AllOrderChildHolder) convertView.getTag(); } return convertView; } } class AllOrderChildHolder{ ImageView icon; TextView goodsName; TextView price; TextView num; }
    转载请注明原文地址: https://ju.6miu.com/read-1294073.html
    最新回复(0)