Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

java - How to get view for an item in listview in android?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...