简体   繁体   中英

Android ListView items disappear when scrolling

I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:

public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{

    private Activity activity;
    List<String> names,facebookbid;
    String sent;

    private  LayoutInflater inflater=null;
    public ImageLoader imageLoader; 

    public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
        activity = a;
        names=n;
        facebookbid=fid;
        sent=s;


        inflater = (LayoutInflater)activity.
                            getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
    }

    @Override
    public int getViewTypeCount() {

        if (getCount() != 0)
            return getCount();

        return 1;
    }


    public int getCount() {
        return facebookbid.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    /********* Create a holder Class to contain inflated xml file elements *********/
    public  class ViewHolder{

        public TextView text;
        public ImageView image;
        public ImageView checkmark;
        public RelativeLayout friendsrow;


    }

    public View getView(final int position, View convertView, ViewGroup parent) {

            convertView=null;


        final ViewHolder holder;

        if(convertView==null){

            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
            convertView = inflater.inflate(R.layout.planners_friends_listrow, null);

            /****** View Holder Object to contain tabitem.xml file elements ******/

            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
          (ImageView)convertView.findViewById(R.id.planner_friend_image);
            holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
            holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);

           /************  Set holder with LayoutInflater ************/
            convertView.setTag( holder );
        }
        else 
            holder=(ViewHolder)convertView.getTag();


        holder.text.setText(names.get(position));




        Typeface   face = Typeface.createFromAsset(convertView.getContext().getAssets(),
                "fonts/MAXWELL REGULAR.ttf");
        holder.text.setTypeface(face);

        ImageView image = holder.image;
      String link;


      if(sent.equals("planners"))
      {link=facebookbid.get(position);

      }
      else
      {
          link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
      }


        //DisplayImage function from ImageLoader Class
        imageLoader.DisplayImage(link, image);


        holder.friendsrow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                boolean a=isNetworkConnected();
                if(a==true)
                {

                    if(sender.equals("settings"))
                    {

                    }
                    else if(sender.equals("savethedate"))
                    {



                        if(sid.contains(facebookbid.get(position)))
                        {
                            if(sid.contains("_"))
                            {
                                sid=sid.replace("_"+facebookbid.get(position), "");
                            }
                            else
                            {
                                sid=sid.replace(facebookbid.get(position), "");
                            }

                            nb_selections--;
                            selectedids.remove(selectedids.size()-1);
                            sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
                            holder.checkmark.setVisibility(View.GONE);
                        }
                        else
                        {
                            if(sid.isEmpty())
                            {
                                sid=sid+facebookbid.get(position);  
                            }
                            else
                            {
                                sid=sid+"_"+facebookbid.get(position);  
                            }

                            nb_selections++;
                            selectedids.add(facebookbid.get(position));
                            sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
                            holder.checkmark.setVisibility(View.VISIBLE);
                        }

                    }
                    else
                    {
                        String friendname=names.get(position);
                        String friendid=facebookbid.get(position);
                        String friendgender=gender.get(position);
                         Intent    resultIntent = new Intent(Friends.this,Newmarriage.class);
                         resultIntent.putExtra("facebookbid", friendid);
                         resultIntent.putExtra("name", friendname);
                         resultIntent.putExtra("gender", friendgender);

                    if(sender.equals("planner"))
                    {
                        resultIntent.putExtra("plannerid",friendid);
                         resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");

                         setResult(Activity.RESULT_OK, resultIntent);
                         finish();  
                    }
                    else
                    {

                        resultIntent.putExtra("plannerid","");
                        resultIntent.putExtra("imageurl","");
                     setResult(Activity.RESULT_OK, resultIntent);
                     finish();  

                    }

                    }   
                }
                else
                {
                    Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();  
                }


            }
        });



        /******** Set Item Click Listner for LayoutInflater for each row ***********/
     //   vi.setOnClickListener(new OnItemClickListener(position));
        return convertView;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }
} 

The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?

Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.

So in short you need something that basically says

if (checked) {
  //set visibility of the checkmark to visible 
} else {
  //set visibility of the checkmark to gone 
} 

First you need to change getView method as don't reinitialize convertView as null remove below line from getView

    public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {

        private Activity activity;
        List<String> names, facebookbid;
        String sent;

        public ImageLoader imageLoader;
        private int size = 0;
        private HashMap<String, Boolean> mapClickStatus;

        public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
            activity = a;
            names = n;
            facebookbid = fid;
            sent = s;
            mapClickStatus = new HashMap<String, Boolean>();


            if (facebookbid != null)
                size = facebookbid.size();
// Give total size of the list item to getCount method
            imageLoader = new ImageLoader(activity, "p");
        }

        @Override
        public int getCount() {

            return size;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        /*********
         * Create a holder Class to contain inflated xml file elements
         *********/
        public class ViewHolder {

            public TextView text;
            public ImageView image;
            public ImageView checkmark;
            public RelativeLayout friendsrow;


        }

        public View getView(final int position, View convertView, ViewGroup parent) {

            // convertView=null;

            //It should not be null every time

            final ViewHolder holder;

            if (convertView == null) {

                /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
                convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);

                /****** View Holder Object to contain tabitem.xml file elements ******/

                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
                (ImageView) convertView.findViewById(R.id.planner_friend_image);
                holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
                holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);

                /************  Set holder with LayoutInflater ************/
                convertView.setTag(holder);
            } else
                holder = (ViewHolder) convertView.getTag();


            holder.text.setText(names.get(position));


            Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
                    "fonts/MAXWELL REGULAR.ttf");
            holder.text.setTypeface(face);

            ImageView image = holder.image;
            String link;


            if (sent.equals("planners")) {
                link = facebookbid.get(position);

            } else {
                link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
            }


            //DisplayImage function from ImageLoader Class
            imageLoader.DisplayImage(link, image);

            // set the visibility of CheckMark ImageView based on the click status.
            if (mapClickStatus.get(facebookbid.get(position)))
                holder.checkmark.setVisibility(View.VISIBLE);
            else
                holder.checkmark.setVisibility(View.GONE);

            holder.friendsrow.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    boolean a = isNetworkConnected();
                    /// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
                    // To set click status of row item in hashmap.
                    mapClickStatus.put(facebookbid.get(position),
                            mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
                    if (a == true) {

                        if (sender.equals("settings")) {

                        } else if (sender.equals("savethedate")) {


                            if (sid.contains(facebookbid.get(position))) {
                                if (sid.contains("_")) {
                                    sid = sid.replace("_" + facebookbid.get(position), "");
                                } else {
                                    sid = sid.replace(facebookbid.get(position), "");
                                }

                                nb_selections--;
                                selectedids.remove(selectedids.size() - 1);
                                sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
                                // holder.checkmark.setVisibility(View.GONE);
                            } else {
                                if (sid.isEmpty()) {
                                    sid = sid + facebookbid.get(position);
                                } else {
                                    sid = sid + "_" + facebookbid.get(position);
                                }

                                nb_selections++;
                                selectedids.add(facebookbid.get(position));
                                sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
                                //  holder.checkmark.setVisibility(View.VISIBLE);
                            }
                            // TO refresh view with updated checkmark status
                            notifyDataSetChanged();
                        } else {
                            String friendname = names.get(position);
                            String friendid = facebookbid.get(position);
                            String friendgender = gender.get(position);
                            Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
                            resultIntent.putExtra("facebookbid", friendid);
                            resultIntent.putExtra("name", friendname);
                            resultIntent.putExtra("gender", friendgender);

                            if (sender.equals("planner")) {
                                resultIntent.putExtra("plannerid", friendid);
                                resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");

                                setResult(Activity.RESULT_OK, resultIntent);
                                finish();
                            } else {

                                resultIntent.putExtra("plannerid", "");
                                resultIntent.putExtra("imageurl", "");
                                setResult(Activity.RESULT_OK, resultIntent);
                                finish();

                            }

                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
                    }


                }
            });


            /******** Set Item Click Listner for LayoutInflater for each row ***********/
            //   vi.setOnClickListener(new OnItemClickListener(position));
            return convertView;
        }

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

        }
    }

Suggestions

  • Inflate layout with parent attaching like below

.

convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
  • Avoid mantaining status by using multiple collection(Arraylist or like that to display data) use Model Class or JSON or Arraylist of map etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM