简体   繁体   English

自定义 ListView 中的视图位置重复

[英]Positions of view in a custom ListView is repeating

I used CustomListAdapter class which extends baseadapter.我使用了扩展 baseadapter 的 CustomListAdapter 类。 In that i have a button on each view of the list view ..when I lick on the button it should print a text.因为我在列表视图的每个视图上都有一个按钮..当我点击按钮时,它应该打印一个文本。 everything is working fine except that the text is printed in someother view too.一切正常,除了文本也打印在其他视图中。 I have found many similar question but no exact solution.我发现了许多类似的问题,但没有确切的解决方案。

 public class CustomListAdapter extends BaseAdapter  {

List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;

  ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2;
ArrayList<String> listItems;

public int count1 = 0;
 ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email;
int i ;
ImageButton like;
ImageButton share;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
  private static String url_all_propertiesdel = IP+"/studio/getdelete_all_agent.php";

  boolean isSelected;
  int a,a1,b,b1;

    //private static final String TAG_SUCCESS1 = "mass";
    private static final String TAG_USER = "users";

    private static final String TAG_PRO = "properties";
    //private static final String TAG_PRO1 = "properties1";
    // products JSONArray
    JSONArray users = null;
    //JSONArray users1 = null;
     View view;

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
 SharedPreferences sPref;
// int position;


public CustomListAdapter(Context context, List<HashMap<String, Object>> models) {
    this.context = context;
    this. models = models;
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.counters = new int[30];

    //this.session_email = sPref.getString("SESSION_UID","");

}

public class ViewHolder {

       public TextView countt;


       public ImageButton like,share;


    }

public void clear(){
    if(models!=null)
        models.clear();
}

@Override
public int getCount() {
    return models.size();
}

public HashMap<String, Object> getItem(int position) {
    return models.get(position);

}

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

@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return position;
} 

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return 1;
}

@Override
public View getView( int position, final View convertView,  ViewGroup parent) {
        //  view = null;
      view = convertView;

          ViewHolder viewHolder;

        pos = getItemViewType(position);
      //  long posn = getItemId(position);
     // final int paps= (int)posn ;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.fragment_home2, parent, false);
            //your code

            //add below code after (end of) your code
            viewHolder.like=(ImageButton)view.findViewById(R.id.likem);
            viewHolder.share=(ImageButton)view.findViewById(R.id.share);

            viewHolder.like.setTag(position);  
          //  viewHolder.share.setTag(position);

          /*  viewHolder.share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    HashMap<String, Object> item = models.get(position);
                            Intent share = new Intent(Intent.ACTION_SEND);

                            // If you want to share a png image only, you can do:
                            // setType("image/png"); OR for jpeg: setType("image/jpeg");
                            share.setType("image/*");

                            // Make sure you put example png image named myImage.png in your
                            // directory
                            String imagePath = Environment.getExternalStorageDirectory()
                                    + "/108.png";

                            String imagePath = (String)item.get("IMAGE");

                            Toast.makeText(context, imagePath, Toast.LENGTH_LONG).show();

                            File imageFileToShare = new File(imagePath);

                            Uri uri = Uri.fromFile(imageFileToShare);
                            share.putExtra(Intent.EXTRA_STREAM, uri);

                            context.startActivity(Intent.createChooser(share, "Share Image!"));



                }


            });*/


           // viewHolder.share.setOnItemClickListener(this);

            viewHolder.like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = (Integer) v.getTag();
                   // viewHolder.countt = (TextView) v.findViewById(R.id.count);
                    HashMap<String, Object> item = models.get(position);
                    isSelected = (Boolean) item.get("selected");
                   item.put("selected", !isSelected);
                  notifyDataSetChanged();




                }
            });
        } else {
           viewHolder = (ViewHolder) view.getTag();
        }




     final HashMap<String, Object> item = getItem(position);



     // like = (ImageView) view.findViewById(R.id.like);
     //sharingButton = (ImageButton) view.findViewById(R.id.share);

  //   final HashMap<String, Object> item1 = getItem(position);
   isSelected = (Boolean) item.get("selected");

     if (isSelected) {

         viewHolder.like.setBackgroundResource(R.drawable.checked);
     } else {
         viewHolder.like.setBackgroundResource(R.drawable.unchecked);
     }


     pic = (ImageView) view.findViewById(R.id.profilePic);
     name = (TextView) view.findViewById(R.id.name);
     idas = (TextView) view.findViewById(R.id.hpid);
     idas2 = (TextView) view.findViewById(R.id.hpid2);
     timestamp = (TextView) view.findViewById(R.id.timestamp);
     msg = (TextView) view.findViewById(R.id.txtStatusMsg);
     url = (TextView) view.findViewById(R.id.txtUrl);
     image = (ImageView) view.findViewById(R.id.feedImage1);
     //countt =(TextView)view.findViewById(R.id.count);
     /*if any exception raises please use 
        locationTitle.setText(((String)item.get(“NAME�?)));
        use this technique for the Image also.
     */
     //holder.like.setText(item.get(item));
     //like.setText((String) item.get(R.id.like));
     idas.setText((CharSequence) item.get("UIDAS"));
    // listItems.add(idas.getText().toString());
     name.setText((CharSequence) item.get("NAME"));
     timestamp.setText((CharSequence) item.get("TIME"));
     msg.setText((CharSequence) item.get("MSG"));
     url.setText((CharSequence) item.get("URL"));









     //countt.setText((CharSequence) item.get("COUN"));
     //count.setText("" + count1);


     int w = image.getWidth();
     int h = image.getHeight();

     if (w > 1000)
     {
          a=w-1000;
          b=w-a;
     }

     else
     {
         b=w;
     }


     if (h > 1000)
     {
          a1=h-1000;
          b1=h-a1;
     }

     else
     {
         b1=h;
     }

        Picasso.with(context)
        //.load("PIC")
     .load((String)item.get("PIC"))
        .placeholder(R.drawable.profile_dummy)
        //.error(R.drawable.ic_whats_hot)
        .resize(50, 50)
    //          .centerCrop()
       // .fit()
        .into(pic);



        /*Display display = getActivity().getWindowManager().getDefaultDisplay(); 
        Point size = new Point();
        display.getSize(size); 
        int width = size.x;*/



     Picasso.with(context)
     .load((String)item.get("IMAGE"))

    //.load("IMAGE")
    // .placeholder(R.drawable.ic_pages)
     //.error(R.drawable.ic_home)
   .resize(1000,b1)
    .onlyScaleDown()
    //.centerCrop()
 // .fit().centerInside()
     .into(image);



     /*if ((image).length() < 0) 
        {   
            //image.setVisibility(View.VISIBLE);
            //  invalid = true;
         idas2.setText(1);
            // Toast.makeText(getApplicationContext(), "hgghghghjgh", Toast.LENGTH_LONG).show(); 

        }*/





    /* delam.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Integer index = (Integer) v.getTag();
                       // pacm = idas.getText().toString();

                        listItems.remove(index.intValue());  
                        notifyDataSetChanged();
                    }
                }

                 );
     */







     /*
     delam.setOnClickListener(new View.OnClickListener() {

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


            pacm = idas.getText().toString();
            removeItemFromList();   

        }


    });
                    */      



   /*  like.setTag(position);   

     like.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            //  int p = (Integer)v.getTag();
                //int p;
            //int posit=(Integer)v.getTag();
                //String s = view[position];
                //Context get = null;
                //Toast.makeText(context, String.valueOf(p)  , Toast.LENGTH_LONG).show();
                //like.setBackgroundResource(R.drawable.checked);

                if( viewHolder.like.isSelected()){
                     viewHolder.like.setSelected(false);
                    //ctv.setBackgroundColor (Color.parseColor("#ffffff"));
                     viewHolder.like.setBackgroundResource(R.drawable.unchecked);


                 }else if(! viewHolder.like.isSelected()){
                     viewHolder.like.setSelected(true);
                        //ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
                     viewHolder.like.setBackgroundResource(R.drawable.checked);



                   }

             }  


        });*/


     return view;
  }



 // HashMap<String, Object> item = models.get(position);





}   

This problem is due to recycling of Viewholder object in your ListView through convertView.此问题是由于通过 convertView 回收了 ListView 中的 Viewholder 对象。 Do not make logic based on the view state as the same state can be passed to some another item of ListView, where it supposed to be presented.不要根据视图状态制定逻辑,因为相同的状态可以传递给 ListView 的另一个项目,在那里它应该被呈现。 So what to do?那么该怎么办? Hold your state on your data Item.将您的状态保持在您的数据项上。 And use notify dataSetChanged when you click some item not change its background Directly.并在单击某个项目时使用 notify dataSetChanged 不直接更改其背景。

You can see example here.您可以在此处查看示例。 That one id for RecyclerView Adapter, but concept is same. RecyclerView Adapter 的一个 id,但概念是一样的。 RecyclerView causes issue when recycling RecyclerView 导致回收时出现问题

Well try this, in your HashMap list you need to have one more item called selected to store selected row status那么试试这个,在你的HashMap列表中,你需要再有一项叫做selected来存储选定的行状态

@Override
public View getView(int position, final View convertView, ViewGroup parent) {
    //your code

    if (view == null) {
        viewHolder = new ViewHolder();
        //your code

        //add below code after (end of) your code
        viewHolder.like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                HashMap<String, Object> item = models.get(position);
                boolean isSelected = (boolean) item.get("selected");
                item.put("selected", !isSelected);
                notifyDataSetChanged();
            }
        });
    } else {
        viewHolder = (ViewHolder) view.getTag();
    }

    //updated
    viewHolder.like.setTag(position);  

    final HashMap<String, Object> item = getItem(position);
    boolean isSelected = (boolean) item.get("selected");

    if (isSelected) {
        viewHolder.like.setBackgroundResource(R.drawable.checked);
    } else {
        viewHolder.like.setBackgroundResource(R.drawable.unchecked);
    }

    //your other code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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