How to get view for an item in listview in android?
Asked Answered
B

5

12

Is it possible to get an item view based on its position in the adapter and not in the visible views in the ListView?

I am aware of functions like getChildAt() and getItemIdAtPosition() however they provide information based on the visible views inside ListView. I am also aware that Android recycles views which means that I can only work with the visible views in the ListView.

My objective is to have a universal identifier for each item since I am using CursorAdapter so I don't have to calculate the item's position relative to the visible items.

Brayer answered 1/1, 2012 at 13:24 Comment(0)
S
8

Here's how I accomplished this. Within my (custom) adapter class:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  View view = null;
  if (convertView == null) {
    LayoutInflater inflater = context.getLayoutInflater();
    view = inflater.inflate(textViewResourceId, parent, false);
    final ViewHolder viewHolder = new ViewHolder();
    viewHolder.name = (TextView) view.findViewById(R.id.name);
    viewHolder.button = (ImageButton) view.findViewById(R.id.button);

    viewHolder.button.setOnClickListener
      (new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        int position = (int) viewHolder.button.getTag();
        Log.d(TAG, "Position is: " +position);
      }
    });

    view.setTag(viewHolder);
    viewHolder.button.setTag(items.get(position));

  } else {
    view = convertView;
    ((ViewHolder) view.getTag()).button.setTag(items.get(position));
  }


  ViewHolder holder = (ViewHolder) view.getTag();

  return view;
}

Essentially the trick is to set and retrieve the position index via the setTag and getTag methods. The items variable refers to the ArrayList containing my custom (adapter) objects.

Also see this tutorial for in-depth examples. Let me know if you need me to clarify anything.

Sikata answered 1/1, 2012 at 14:36 Comment(1)
I thought of this approach. In CursorAdapter bindView replaces getView, I attempted to set a tag for each view using this code: id.setText(cursor.getString(cursor.getColumnIndexOrThrow("id"))); however, for some reason the id was every other number instead of being continuous. Anyway, I will review my code based on the example you provided.Brayer
A
3

See below code:

 public static class ViewHolder
{
    public TextView nm;
    public TextView tnm;
    public TextView tr;
    public TextView re;
    public TextView membercount;
    public TextView membernm;
    public TextView email;
    public TextView phone;
    public ImageView ii;
}
class ImageAdapter extends ArrayAdapter<CoordinatorData> 
{
    private ArrayList<CoordinatorData> items;
    public FoodDriveImageLoader imageLoader;
    public ImageAdapter(Context context, int textViewResourceId,ArrayList<CoordinatorData> items) 
    {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    public View getView(int position, View convertView, ViewGroup parent) 
    {
        View v = convertView;
        ViewHolder holder = null;
        if (v == null) 
        {
            try
            {
                holder=new ViewHolder();
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                imageLoader =   new FoodDriveImageLoader(FoodDriveModule.this); 
                v = vi.inflate(R.layout.virtual_food_drive_row, null);
                //System.out.println("layout is null.......");
                holder.nm = (TextView) v.findViewById(R.id.name);
                holder.tnm = (TextView) v.findViewById(R.id.teamname);
                holder.tr = (TextView) v.findViewById(R.id.target);
                holder.re = (TextView) v.findViewById(R.id.received);
                holder.membercount = new TextView(FoodDriveModule.this);
                holder.membernm = new TextView(FoodDriveModule.this);
                holder.email = new TextView(FoodDriveModule.this);
                holder.phone = new TextView(FoodDriveModule.this);
                holder.ii = (ImageView) v.findViewById(R.id.icon);

                v.setTag(holder);
            }
            catch(Exception e)
            {
                System.out.println("Excption Caught"+e);
            }
        }
        else
        {
            holder=(ViewHolder)v.getTag();
        }
        CoordinatorData co = items.get(position);
        holder.nm.setText(co.getName());
        holder.tnm.setText(co.getTeamName());
        holder.tr.setText(co.getTarget());
        holder.re.setText(co.getReceived());
        holder.ii.setTag(co.getImage());

        imageLoader.DisplayImage(co.getImage(), FoodDriveModule.this , holder.ii);

        if (co != null) 
        {
        }
        return v;
    }

}
Amaryllis answered 2/1, 2012 at 10:7 Comment(0)
Q
1

A better option is to identify using the data returned by the CursorAdapter rather than visible views. For example if your data is in a Array , each data item has a unique index.

Quickfreeze answered 1/1, 2012 at 14:24 Comment(4)
Is there any particular function that I can use? I read the entire list of CursorAdapter functions but none of them seems to get the view based on id apart from getView() which is not recommended to use externally.Brayer
What is the data structure you are using to populate the list?Quickfreeze
I populate the list from a Sqlite database through CursorAdapterBrayer
I ended up using getFirstVisiblePosition(). Apparently it returns the item id relative to the entire list and not just the visible views. I then calculate the position of the item that I wanted based on that. Thank you.Brayer
O
0

Here, Its very short described code, you can simple re-use viewholder pattern to increase listview performance Write below code in your getview() method

ViewHolder holder = new ViewHolder();
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.skateparklist, null);
        holder = new ViewHolder();

        holder.headlineView = (TextView) convertView
                .findViewById(R.id.textView1);
        holder.DistanceView = (TextView) convertView
                .findViewById(R.id.textView2);
        holder.imgview = (NetworkImageView) convertView
                .findViewById(R.id.imgSkatepark);
        convertView.setTag(holder); //PLEASE PASS HOLDER AS OBJECT PARAM  , CAUSE YOU CAN NOY PASS POSITION IT WILL BE CONFLICT Holder and Integer can not cast 
        //BECAUSE WE NEED TO REUSE CREATED HOLDER 
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

// your controls/UI setup 
    holder.DistanceView.setText(strDistance); 
    ......
   return convertview
Odrick answered 3/9, 2014 at 5:25 Comment(0)
P
0
Listview lv = (ListView) findViewById(R.id.previewlist);

    final BaseAdapter adapter = new PreviewAdapter(this, name, age);

    confirm.setOnClickListener(new OnClickListener() {

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


            View view = null;

            String value;
            for (int i = 0; i < adapter.getCount(); i++) {

                view = adapter.getView(i, view, lv);

                Textview et = (TextView) view.findViewById(R.id.passfare);


                value=et.getText().toString();

                 Toast.makeText(getApplicationContext(), value,
                 Toast.LENGTH_SHORT).show();
            }



        }
    });
Paving answered 26/3, 2016 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.