Android 咨询项目之listView多条目

listView多条目很常见 像头条什么的一些App都很常见
今天就简单剖析一下多条目

适配器
首先多条目 我们要实现两个方法
getViewTypeCount ->多少种条目
getItemViewType—>获取当前条目的类型 0,1,2,3

  
       //有多少种类型;
        @Override
        public int getViewTypeCount() {
            return 2;
        }

         //条目的类型用int值来区分, 从0开始排序,0123....
        @Override
        public int getItemViewType(int position) {

            if (position % 2 == 0) {
                return 0;
            } else {
                return 1;
            }

        }

然后getView方法 switch判断一下类型 分别写一下

 @Override
        public View getView(int position, View view, ViewGroup viewGroup) {

            int viewType = getItemViewType(position);
            switch (viewType) {
                case 0: //偶数条目 返回文字+图片条目;
                    ViewHolder0 viewHolder0;
                    if (view == null) {
                        viewHolder0 = new ViewHolder0();
                        view = View.inflate(MainActivity.this, R.layout.lv_item_00, null);
                        viewHolder0.textView1 = view.findViewById(R.id.textView1);
                        viewHolder0.textView2 = view.findViewById(R.id.textView2);
                        viewHolder0.imageView = view.findViewById(R.id.imageView);
                        view.setTag(viewHolder0);
                    } else {
                        viewHolder0 = (ViewHolder0) view.getTag();
                    }
                    viewHolder0.textView1.setText(list.get(position).getNews_id());
                    viewHolder0.textView2.setText(list.get(position).getNews_title());
                    imageLoaderInstance.displayImage(list.get(position).getPic_url(), viewHolder0.imageView);

                    break;
                case 1: // 奇数条,只返回文字条目
                    ViewHolder1 viewHolder1 = null;
                    if (view == null) {
                        viewHolder1 = new ViewHolder1();
                        view = View.inflate(MainActivity.this, R.layout.lv_item_11, null);
                        viewHolder1.tv1 = (TextView) view.findViewById(R.id.tv1);
                        viewHolder1.tv2 = (TextView) view.findViewById(R.id.tv2);
                        view.setTag(viewHolder1);
                    } else {
                        viewHolder1 = (ViewHolder1) view.getTag();
                    }
                    viewHolder1.tv1.setText(list.get(position).getNews_id());
                    viewHolder1.tv1.setText(list.get(position).getNews_title());

                    break;

            }

            return view;
        }
        private class ViewHolder0 {
        private TextView textView1;
        private TextView textView2;
        private ImageView imageView;
    }

    private class ViewHolder1 {
        private TextView tv1;
        private TextView tv2;
    }

你可能感兴趣的:(Android 咨询项目之listView多条目)