Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Holder And custom list view items getting shuffled while scrolling

I know there is a lot of similar questions out there but i cant find the mistake i am making,if anybody could help. I am trying to display the values in an array list like a chat format but the array list items are getting misplaced on scrolling

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

            final ViewHolder holder;
            if (convertView == null) {

                convertView = LayoutInflater.from(getActivity()).inflate(
                        R.layout.chat_row, parent, false);
                holder = new ViewHolder();
     holder.messageLeft = (TextView) convertView
                    .findViewById(R.id.leftBox);
            holder.messageRight = (TextView) convertView
                    .findViewById(R.id.rightBox);
      convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            try { if (snd_id.get(position).equalsIgnoreCase(appPref.getData("Uid"))) {
                holder.messageLeft.setText(snd_name.get(position)+":"+"\n"+chat.get(position));
                holder.messageLeft.setVisibility(View.VISIBLE);
                holder.messageRight.setVisibility(View.GONE);
            } else {
                holder.messageRight.setText(snd_name.get(position)+":"+"\n"+chat.get(position));
                holder.messageRight.setVisibility(View.VISIBLE);
                holder.messageLeft.setVisibility(View.GONE);
            }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return convertView;

        }

here is the view holder class

private static class ViewHolder {
        public TextView messageLeft;
        public TextView messageRight;
    }
like image 287
George Thomas Avatar asked Feb 13 '23 15:02

George Thomas


1 Answers

Just include holder.messageRight.setVisibility(View.GONE); and holder.messageLeft.setVisibility(View.GONE); in your if-else statement.

 try {
        if (snd_id.get(position).equalsIgnoreCase(appPref.getData("Uid"))) {
            holder.messageLeft.setText(snd_name.get(position)+":"+"\n"+chat.get(position));
            holder.messageLeft.setVisibility(View.VISIBLE);
            holder.messageRight.setVisibility(View.GONE);
        } else {
            holder.messageRight.setText(snd_name.get(position)+":"+"\n"+chat.get(position));
            holder.messageRight.setVisibility(View.VISIBLE);
            holder.messageLeft.setVisibility(View.GONE);
        }

Let me know whether it works for you or not.

like image 100
user370305 Avatar answered May 01 '23 13:05

user370305