android:how to make infinite scrollview with endless scrolling

前端 未结 2 1381
旧巷少年郎
旧巷少年郎 2021-01-05 07:54

I want a code to make the ScrollView show the same images with endless scrolling over and over.

This is excelent for the layout and I want to know what

2条回答
  •  轮回少年
    2021-01-05 08:20

    FoamGuy's answer is correct. But in order to make the list go backwards, as in an infinite carrousel, I also trick the system by setting the default element to be Integer.MAX_VALUE/2 by calling:

    listView.setSelection( Integer.MAX_VALUE/2 );
    

    It is pretty unlikely the user will scroll back 1 billion elements back, which makes the effect of infinite carrousel in both directions.

    I also have some other modifications to the BaseAdapter custom implementation:

    @Override
    public Object getItem(int position) {
        if ( model.getSize()==0 ) {
            return null;
        }
    
        // mod the list index to the actual element count
        return model.getElementAtPosition( position%model.getSize() );
    }
    
    @Override
    public long getItemId(int position) {
        if ( model.getSize()==0 ) {
            return -1;
        }
    
        // same as above
        return model.getElementAtPosition( position%model.getSize() ).id;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        if ( model.getSize()==0 ) {
            return null;
        }
    
        // also make sure to point to the appropriate element in your model otherwise you 
        // would end up building millions of views.
        position%=model.getSize();
    
        View front= convertView;
    
        if ( convertView==null ) {
            // inflate/build your list item view
        }
    
        ...
    }
    

    This way the list will spin around like in a carousel w/o extra memory allocation for unneeded views.

提交回复
热议问题