onTouchListener不使用自定义视图

时间:2016-02-08 14:44:44

标签: android android-custom-view ontouchlistener

我有一个自定义适配器类,它扩展了基本适配器。我正在尝试在视图项上实现onTouchListener。但它没有用。请帮忙。

以下是代码段

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

    if(cellView==null) {

        LayoutInflater layoutInflater = (LayoutInflater) context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        cellView = layoutInflater.inflate(R.layout.grid_topics, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.icon = (ImageView) cellView.findViewById(R.id.cellImageView);
        viewHolder.text = (TextView) cellView.findViewById(R.id.cellTextView);
        cellView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) cellView.getTag();
    }

    viewHolder.icon.setImageBitmap(list.get(position).image);
    viewHolder.text.setText(list.get(position).text);

    cellView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_UP) {
                Toast.makeText(context, list.get(position).text, Toast.LENGTH_SHORT).show();
                return true;
            }

            return false;
        }
    });
    return cellView;
}

1 个答案:

答案 0 :(得分:0)

在处理BaseAdapter时尝试遵循此方法。看看我如何在if语句中实现onTouch监听器。这应该有用。

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;

    LayoutInflater mInflater = (LayoutInflater) 
        context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
        holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
        holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
        convertView.setTag(holder);
        convertView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_UP) {
            Toast.makeText(context, list.get(position).text, Toast.LENGTH_SHORT).show();
            return true;
        }

        return false;
    }
});
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }

    RowItem rowItem = (RowItem) getItem(position);

    holder.txtDesc.setText(rowItem.getDesc());
    holder.txtTitle.setText(rowItem.getTitle());
    holder.imageView.setImageResource(rowItem.getImageId());

    return convertView;
}