madhu makwana madhu makwana - 1 year ago 73
Android Question

Images are repeated in horizontal ListView in android

I am stuck in an issue related to horizontal ListView in android,I have created a custom horizontal ListView with imageView as a row,All is working as i needed,But problem i am facing is the first and last row gets duplicated.I am posting my code for it.

HorizonAdapter

public class HorizonAdapter extends BaseAdapter {
private Context mContext;
private final ArrayList<String> imgs;

public HorizonAdapter(Context c, ArrayList<String> imgs) {
mContext = c;
this.imgs = imgs;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return imgs.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

if (convertView == null) {

grid = new View( mContext );
grid = inflater.inflate( R.layout.raw_product, null );
ImageView imageView = (ImageView) grid.findViewById( R.id.iv_product );
System.out.print( "======IMAGE=====>"+imgs.get( position ) );
Picasso.with( mContext )
.load( imgs.get( position ).replaceAll(" ", "%20") )
.placeholder( R.drawable.ic_no_img )
.error( R.drawable.ic_no_img )
.into( imageView );
} else {
grid = (View) convertView;
}

return grid;
}
}

Answer Source

change this in your adapter class

@Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return  position;
    }

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View grid;
    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService( Context.LAYOUT_INFLATER_SERVICE );

    if (convertView == null) {

        grid = new View( mContext );
        grid = inflater.inflate( R.layout.raw_product, null );
    } else {
        grid = (View) convertView;
    }
    ImageView imageView = (ImageView) grid.findViewById( R.id.iv_product );
        System.out.print( "======IMAGE=====>"+imgs.get( position ) );
        Picasso.with( mContext )
                .load( imgs.get( position ).replaceAll(" ", "%20") )
                .placeholder( R.drawable.ic_no_img )
                .error( R.drawable.ic_no_img )
                .into( imageView );

    return grid;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download