Android BaseAdapter getView - 任何获得真实位置的方法?

时间:2014-04-11 16:20:58

标签: android listview

  public View getView(int position, View convertView, ViewGroup parent) {

这里的位置不是ListView中的实际位置,因为它们被回收并且我需要知道真实的位置,例如,如果它在ListView中的第24个位置我需要知道它是否是24。 / p>

  @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
            if (view == null) { 

     view = lInflater.inflate(R.layout.item, parent, false);

              }


                imgstatus=(ImageView) view.findViewById(R.id.ivImage);
          imgstatus.setTag(position);
          itemTap=view.findViewById(R.id.itemTap);
          itemTap.setTag(position);


//....there's a lot of stuff, but I set Tags here
}

所以,问题是当我在这些元素上设置onClick或onTouchListeners时 - 它会返回错误的标签。

例如,当我打开它并向下滚动时 - 标签就可以了。 16是16,但是当我向上和向下滚动时,16可能变为2

获取标签:

 itemTap.setOnTouchListener(new View.OnTouchListener() {


                @Override
                public boolean onTouch(View v, MotionEvent event) {
    //skipped
    if (event.getAction()==MotionEvent.ACTION_UP){
                        downtime=0L;
                        Log.d("MyLog","up. tag="+v.getTag());
                        listener_item.itemClick((Integer) v.getTag());  
                        (((RelativeLayout) v.getParent()).findViewById(R.id.ivAllother)).setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.spare_play));
                        return true;
                    }
}

所以,在这里,Log.d("MyLog","up. tag="+v.getTag());在我滚动我的ListView之后返回错误的标签

4 个答案:

答案 0 :(得分:1)

来自official doc

/** 
   position The position of the item within the adapter's data set of the item whose view we want.
**/
public abstract View getView (int position, View convertView, ViewGroup parent)

你的假设不正确。位置不受回收影响。它始终显示实际位置:项目在数据集中的位置。

答案 1 :(得分:1)

使用getPositionForView方法,因为@udp说:

public View getView(int position, View convertView, ViewGroup parent) {

    int listPosition;    

    if(convertView != null) {
        listPosition = ((ListView)parent).getPositionForView(convertView);
    }

}

答案 2 :(得分:0)

private OnClickListener mButton = new OnClickListener() {
    @Override
    public void onClick(View v) {
    final int realPosition = mListView.getPositionForView((View) v.getParent());
        // do stuff
    }
};

答案 3 :(得分:0)

您可以position final使用

访问onTouch方法
listener_item.itemClick(position);