2016-02-08 62 views
-1

我有一個自定義的適配器類,它擴展了基礎適配器。我試圖在視圖項目上實現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; 
} 

回答

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; 
} 
+0

不,它仍然沒有工作。你的代碼與我的代碼有什麼不同? –