GrivView的BaseAdapter中的绝对位置

时间:2011-11-29 17:14:42

标签: android android-layout android-gridview android-adapter

我正在尝试将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  | 

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

编辑:然而,即使在屏幕上,返回的数字也比我显示的更随机。

1 个答案:

答案 0 :(得分:1)

使用与Google Documentatnion完全相同的BaseAdapter显示效果正常。

我的问题是:

  • 使用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;
}