问题
I'm trying to write BaseAdapter
to my GrivView
but in
public View getView(int position, View convertView, ViewGroup parent) { ... }
the position
while rendering next elements is:
visible elements
---------------
| 1 2 3 |
| 4 5 6 | <--- screen
| 7 8 9 |
---------------
nonvisible elements
| 1 2 3 | <-- below visible area
| 4 5 6 |
where real is:
visible elements
---------------
| 1 2 3 |
| 4 5 6 |
| 7 8 9 |
---------------
nonvisible elements
| 10 11 12 |
| 13 14 15 |
I'm aware it's correct behaviour (it counts only visible elements), but how to get the real position of item on list? Or how to know which layout should I return?
EDIT: However the returned number are much more random than I showed, even on screen.
回答1:
Using BaseAdapter
exactly like Google Documentatnion shows works fine.
My problem was:
NOT using ViewHolder
or trying to hold id in viewHolder
I should to use ViewHolder
as following:
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;
}
来源:https://stackoverflow.com/questions/8314859/absolute-position-in-baseadapter-of-grivview