i_me_mine
i_me_mine

Reputation: 1433

getView problems setting Listener with position

I have a ListView with an Adapter that is using a LruCache as it's ViewHolder. I'm attempting to retrieve a View from the cache inside getView() and set a onLongClickListener. However despite my efforts I seem to get the last index in my cache every single time.

Adapter

private class MyAdapter extends BaseAdapter {
        private LruCache<Integer, View> mViewCache;
        private Context mContext;
        private LayoutInflater mInflater;

        private MyAdapter(Context context) {
            mContext = context;
            mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mViewCache = new LruCache<Integer, View>(10);
        }

        private View inflateMyView(ViewGroup parent, View view) {
            view = mInflater.inflate(R.layout.my_row, null);
            return view;
        }

getView

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = mViewCache.get(position);

    if (view == null) {
        view = inflateMyView(parent, null);
        mViewCache.put(position, view);
    }
    ...
    ...
view.setOnLongClickListener(new OnLongClickListener() {

So as you can now see my onLongClickListener only works on the last item I added to my list(last index in my cache). I need each item in my list to have this Listener attached, not just the last. Any help is appreciated, I've been staring at this too long.

Edit (FYI)
Due to the tightly coupled nature of this code the onLongClickListener must remain inside getView. Which is why I'm so frustrated. If this has to move it becomes a totally different solution

Upvotes: 0

Views: 84

Answers (1)

betteroutthanin
betteroutthanin

Reputation: 7546

Remove view.setOnLongClickListener(new OnLongClickListener() in your getView method and let it return convertView. set the onLongClickListener after you setting the adapter for your ListView:

listView.setAdapter(new MyAdapter(this));

listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            return false;
        }

});

Upvotes: 1

Related Questions