0

I have an InfoListAdapter that uses the following code to populate views in the list:

    public InfoListAdapter(final Context context) {
        super(context, 0);
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder viewHolder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.info_list_item, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.populateViews(getItem(position));

        return convertView;
    }
}

I am wondering how I can follow this ViewHolder pattern and still add an onClickListener that will launch another activity DetailListActivity when clicked. My stragey was to make the mListener change using the existing populateViews method.

Needless to say it does not work. I think part of the problem here is that since mListener is null when I set the onClickListener, that reference is retained even after I change the value of the mListener. But the deeper question is how do I set something like this up, where I can use the ViewHolder pattern and let populateViews do the decoration (in terms of adding a listener to the click action)?

class ViewHolder {
    private TextView mTextViewDisplayName;
    private OnClickListener mListener;
    private Context mContext;

    public ViewHolder(final View view) {
        mTextViewDisplayName = (TextView) view.findViewById(R.id.tv_displayname);
        view.setOnClickListener(mListener);
        mContext = view.getContext();
    }

    public void populateViews(final Info infoItem) {
        mTextViewDisplayName.setText(infoItem.displayName);

        mListener = new OnClickListener() {

        public void onClick(View view0) {
                Intent mIntent = new Intent(mContext, DetailActivity.class);
                mIntent.putExtra(EMService.INTENT_EXTRA_DETAIL_VIEW_SOMEPARAM, 0);
                startActivityForResult(mIntent, 0);
            }
        };
    }
}
4

1 回答 1

1

In your parent activity/fragment that houses your ListView you can implement OnItemClickListener and handle your clicks there. This way you don't have to assign a click handler for every single view you instantiate.

Ex. Lets say you have a ListActivity class named MyListActivity (I'm so creative)

public class MyListActivity extends ListActivity implements OnItemClickListener
{
    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id)
    {
        Intent intent = new Intent(this, DetailActivity.class);
        intent.putExtra(EMService.INTENT_EXTRA_DETAIL_VIEW_SOMEPARAM, 0);
        startActivityForResult(intent, 0);
    }

}
于 2012-04-12T18:05:59.670 回答