I’ve got a GridView which i should fill with two different items such as left_item and right_item. Anyway, i wrote a custom adapter extended from BaseAdapter.
And i saw converted views were not in ordered how i thought. So i was seeing my GridView like this:
Left Right
Right Left
Left Right
Left Right
Right Left
… …
And so on. I’ve found a solution this to order as well. But my question is if my solution is a right way to approach this problem or not? Here’s my Custom Adapter and my solution:
class MyGridAdapter extends BaseAdapter {
// return even count in any case
public int getCount() {
if (items.size() % 2 == 0)
return items.size();
else
return (items.size() + 1);
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// Here, i thought that i was gonna have
// converted views one left one right, but i didn't!
if (v == null) {
if (position % 2 == 0) {
// inflate left side
v = inflater.inflate(R.layout.left_shelf_item, null);
} else {
// inflate right side
v = inflater.inflate(R.layout.right_shelf_item, null);
}
}
if (position % 2 == 0) {
// So i had to inflate left view, if i'm not getting that
if(v.getId() != R.layout.left_shelf_item)
v = inflater.inflate(R.layout.left_shelf_item, null);
if (position != items.size()) {
ImageView img = (ImageView) v
.findViewById(R.id.leftShelfItemBook);
if (img != null) {
int bookId = Integer.parseInt(items.get(position)
.getBookId());
if (images.get(bookId) != null) {
img.setImageDrawable(Drawable.createFromPath(images
.get(bookId)));
} else {
img.setImageDrawable(null);
}
}
}
} else {
// And here, i do the same for right
if(v.getId() != R.layout.right_shelf_item)
v = inflater.inflate(R.layout.right_shelf_item, null);
if (position != items.size()) {
ImageView img = (ImageView) v
.findViewById(R.id.rightShelfItemBook);
if (img != null) {
int bookId = Integer.parseInt(items.get(position)
.getBookId());
if (images.get(bookId) != null) {
img.setImageDrawable(Drawable.createFromPath(images
.get(bookId)));
} else {
img.setImageDrawable(null);
}
}
} else if (position == items.size()) {
((View) v.findViewById(R.id.rightShelfItemHolder))
.setVisibility(View.GONE);
}
}
return v;
}
}
As you see, i forced adapter to use correct view by inflating views again if they’re not the ones they’re supposed to be.
Because of this, i’m very concern of having memory leak and getting OutOfMemoryError, or some other errors caused by inflating too much.
Is there any other way to achieve this? I need a better solution, please. Any help or information would be appreciated.