自定义适配器:点击获取项目的项目数量膨胀的列表视图项目、自定义、适配器、视图

2023-09-05 04:24:32 作者:煮酒问寒秋

我有一个自定义baseadapter,做一些图像的一些延迟加载,然后充气的布局,所以我结束了一个列表视图,我有图像和文字在一排。

I have a custom baseadapter which does some lazy loading of some images, and then inflating the layout so I end up with a listview where I have both image and text in one row.

当用户presses列表视图中的一个项目,例如说,项目0(顶部项),我想展示一些具体内容的对话框。此含量取决于项目数 - 所以示出为项0的内容不一样的第1项,依此类推

When the user presses one item of the listview, say for example item 0 (top item), I want to show a dialog box with some specific content. This content depends on the item number - so the content shown for item 0 is not the same as for item 1, and so on.

下面是自定义适配器的 getView 方法:

Here is the getView method of the custom adapter:

public View getView(int position, View convertView, ViewGroup parent)
{
    View vi=convertView;        
    if(convertView==null)
    {
        vi = inflater.inflate(R.layout.facebook_item, null);                        
        vi.setClickable(true);
        vi.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {                   
                String s = "test";
                Toast.makeText(myContext, s, Toast.LENGTH_SHORT).show();
            }
        });
    }        

    TextView text=(TextView)vi.findViewById(R.id.text);
    ImageView image=(ImageView)vi.findViewById(R.id.image);
    text.setText(msg[position]);
    text.getLineCount();
    imageLoader.DisplayImage(data[position], image);
    return vi;
}

这里的关键是什么办法去上的onClick。我想有一个项目的参数,但是这是不可能的这个OnClickListener。这是可能的正常列表视图,我知道。

What's important here is what's going on in the onClick method. I would like to have an item parameter, but this is not possible for this OnClickListener. It's possible for normal listviews, I know that.

所以 - 我怎么能确定被点击哪个项目

So - how can I determine which item is clicked?

PS:我一直在努力,想使用某种 vi.setTag的(小于<数量>>); ,但我没有看到如何可以在不具有相同标签的列表视图的所有项目设置完成。

PS: I've tried to think of using some sort of vi.setTag(<<number>>);, but I don't see how this can be done without having the same tag set for all items of the listview.

推荐答案

为什么不上的ListView本身使用onItemClickListener?

Why not use onItemClickListener on ListView itself?

您适配器应该包含一个对象类型列表(没有严格的规则,但它可以帮助管理项目更容易)。例如

Your Adapter should contain a List of one Object type (there is no strict rule, but it helps managing the item much easier). For example

class MsgObject{
    String msg;
    String data

    //TODO Getters/Setters goes here
}

那么你的CustomAdapter将只包含

Then your CustomAdapter will only contain

List<MsgObject> objectList;

那么你的getView将类似于这样

Then your getView will looks similar to this

    MsgObject m = (MsgObject)getObject(position);
    TextView text=(TextView)vi.findViewById(R.id.text);
    ImageView image=(ImageView)vi.findViewById(R.id.image);
    text.setText(m.getMsg());
    text.getLineCount();
    imageLoader.DisplayImage(m.getData(), image);
    //Tag id is predefined in xml
    vi.setTag(R.id.listItemTag, m);
    return vi;

现在你的观点会处理这作为一个对象,而不是多个值中的一个布局。

Now your view will handle this as one object instead of one layout with multiple values.

然后,我们将所有的点击动作到ListView控件驻留在活动。

Then we move all the click action to the Activity which ListView resides in.

listView.setOnItemClickListener(){
    new AdapterView.OnItemClickListener(){

        @override
        public onItemClick(AdapterView<?> parent, View view, int position, long id){
            MsgObject m = (MsgObject)view.getTag(R.id.listItemTag);
            Toast.makeText(context, "Pos[" + position 
                + "] clicked, with msg: " + m.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

};

这是方式,我有我的ListView与延迟加载ImageView的为好。然后,你将能够访问绑定到这个观点也被点击的对象。

This is the way I have my ListView with Lazy load ImageView as well. Then you will be able to access the object tied to that view and also the position which is clicked.

如果你是这样想味精和数据分开。您可以使用setTag(ID,OBJ);这两个对象,等等。

If you are so wish to separate msg and data. You can use setTag(id, obj); for both object, etc.

setTag(R.id.listItemMsg, msg[position]);
setTag(R.id.listItemData, data[position]);

更新:我CustomAdapter的例子​​

UPDATE: Example of my CustomAdapter

/**
 * Adapter for displaying Place selection list.
 * @author Poohdish Rattanavijai
 *
 */    
public class PlaceAdapter extends BaseAdapter {
    private static final String TAG = PlaceAdapter.class.getSimpleName();
    private List<PlaceVO> list; // <-- list of PlaceVOs
    private Context context;
    private int viewResourceId;

    /**
     * 
     * @param context Context
     * @param viewResourceId Layout ID for each item
     * @param list resource list to populate
     */
    public PlaceAdapter(Context context, int viewResourceId, List<PlaceVO> list){
        this.context = context;
        this.viewResourceId = viewResourceId;
        this.list = list;
    }

    /**
     * Number of result in the list plus one (for +add at the last item)
     */
    @Override
    public int getCount() {

        if(null != list){
            return list.size();
        }

        return 1;
    }

    @Override
    public Object getItem(int arg0) {
        if(null != list){
            try {
                return list.get(arg0);
            } catch (IndexOutOfBoundsException e) {
                return null;
            }
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
//      if(null != list){
//          try {
//              return list.get(position).getId();
//          } catch (IndexOutOfBoundsException e) {
//              return 0;
//          }
//      }
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(null == convertView){
            /**
             * View does not exist, populate.
             */
            LayoutInflater inflater = LayoutInflater.from(this.context);
            convertView = inflater.inflate(this.viewResourceId, parent, false);
        }
        ViewHolder holder = (ViewHolder)convertView.getTag(R.id.adpter_view);

        if(null == holder){
            Log.d(TAG, "holder not found, init.");
            /**
             * ViewHolder does not exists for this view; create and assign respective view.
             */
            holder = new ViewHolder();
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.details = (TextView) convertView.findViewById(R.id.details);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            holder.progress = (ProgressBar) convertView.findViewById(R.id.progress);
        }

        PlaceVO v = (PlaceVO)getItem(position); // <-- GetItem

        if(null != v){
            Log.d(TAG, "Place not null");
            if(HelperUtil.IsNotNullOrEmpty(v.getName())){
                Log.d(TAG, "Name: " + v.getName());
                holder.title.setText(v.getName());
            }

            if(HelperUtil.IsNotNullOrEmpty(v.getVicinity())){
                Log.d(TAG, "details: " + v.getVicinity());
                holder.details.setText(v.getVicinity());
            }

            if(HelperUtil.IsNotNullOrEmpty(v.getIcon())){
                holder.progress.setVisibility(View.VISIBLE);
                holder.icon.setVisibility(View.GONE);
                            //TODO Initialize LazyLoad
            }else{
                holder.progress.setVisibility(View.VISIBLE);
                holder.icon.setVisibility(View.GONE);
            }
        }
            // Two tags, one for holder, another for the VO
        convertView.setTag(R.id.adpter_view, holder);
        convertView.setTag(R.id.adpter_object, v);
        return convertView;
    }

    static class ViewHolder{
        TextView title;
        TextView details;
        ImageView icon;
        ProgressBar progress;
    }
}

里面的活动我处理项目点击行动

Inside Activity I handle item click action with

OnItemClickListener itemClick = new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                PlaceVO v = (PlaceVO)arg1.getTag(R.id.adpter_object); // <-- get object using tag.
                switchToPlaceScreen(v);
            }
        };
listView.setOnItemClickListener(itemClick);

希望这回答你的问题:)

Hope this answer your question :)

 
精彩推荐
图片推荐