4

我正在尝试写信BaseAdapter给我GrivView,但在

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

position渲染下一个元素的同时是:

visible elements
---------------
|  1   2   3  |
|  4   5   6  | <--- screen
|  7   8   9  |
---------------

nonvisible elements
|  1   2   3  | <-- below visible area
|  4   5   6  |

真正的地方是:

visible elements
---------------
|  1   2   3  |
|  4   5   6  | 
|  7   8   9  |
---------------

nonvisible elements
| 10  11  12  |
| 13  14  15  | 

我知道这是正确的行为(它只计算可见元素),但是如何获取列表中项目的实际位置?或者如何知道我应该返回哪个布局?

编辑:但是返回的数字比我显示的随机得多,即使在屏幕上也是如此。

4

1 回答 1

1

使用与Google DocumentatnionBaseAdapter完全一样的节目效果很好。

我的问题是:

  • 使用 ViewHolder

  • 或试图在 viewHolder 中保留 id

我应该使用ViewHolder如下:

public View getView(int position, View convertView, ViewGroup parent) {
    // create holder
    ViewHolder holder; // check if layout exists

    if (convertView == null) { // if it's not recycled, initialize some

        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = (LinearLayout) inflater.inflate(R.layout.card_prev,
                null);

        // Create layout elements
        ImageView image = (ImageView) convertView
                .findViewById(R.id.imageViewThumbnail);

        TextView desc = (TextView) convertView
                .findViewById(R.id.textViewDescription);


        // Place layout elements in holder
        holder = new ViewHolder();
        holder.id = position;
        holder.preview = image;
        holder.text = desc;

        convertView.setTag(holder);
    } else {
        // Get existing holder
        holder = (ViewHolder) convertView.getTag();
    }

    // Update layout here using layout elements from holder
    String imageName = "image_" + (position + 1);
    final int imageId = mContext.getResources().getIdentifier(imageName,
            "drawable", "com.myapp");

    holder.text.setText("" + (position+1));

    holder.preview.setImageResource(imageId);

    holder.preview.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent fullScreenIntent = new Intent(v.getContext(),
                    FullScreenImage.class);
            fullScreenIntent.putExtra("imageRes", imageId);

            MainMenuActivity.currentShownActivity
                    .startActivity(fullScreenIntent);

        }
    });

    return convertView;
}
于 2011-11-29T22:35:04.573 回答