本文实例为大家分享了Android无限循环滚动的具体代码,供大家参考,具体内容如下
因项目需要循环展示列表数据,所以就实现了这个无限循环滚动的 LIstView.先说一下原理,原理呢,其实很简单,首先将要展示的数据循环展示三遍
监听ListView的滚动事件,当ListView滚动到第一遍第第二个时,ListView变自动跳到第二遍的第二个,同理,如果ListView滚动到倒数第一个时,ListView自动跳转到第二遍的倒数第一个,然后可以不停的向上或者向下滑动,永远不会到头,废话少说,上
代码:
让ListView循环三遍展示
首先利用取余的方法,将List里面的数据循环展示
代码语言:javascript复制public class ListAdapter extends BaseAdapter {
private List<String list;
private LayoutInflater mInflater;
public ListAdapter(Context context, List<String list){
this.list = list;
this.mInflater = LayoutInflater.from(context);
}
/**
* 将数据循环展示三遍
*/
@Override
public int getCount() {
if(list != null){
return list.size() * 3;
}
return 0;
}
@Override
public Object getItem(int arg0) {
return list.get(arg0 % list.size());
}
@Override
public long getItemId(int arg0) {
return arg0 % list.size();
}
@Override
public View getView(int postition, View convertView, ViewGroup arg2) {
ViewHoler viewHolder = null;
if(convertView == null){
viewHolder = new ViewHoler();
convertView = mInflater.inflate(R.layout.adapter_list_layout, null);
viewHolder.tvText = (TextView) convertView.findViewById(R.id.adapter_list_layout_tv);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHoler) convertView.getTag();
}
viewHolder.tvText.setText(list.get(postition % list.size()));//取余展示数据
return convertView;
}
static class ViewHoler{
TextView tvText;
}
}
然后实现监听ListView的滚动事件
代码语言:javascript复制public class MainActivity extends Activity implements OnScrollListener {
private ListView listView;
private List<String list;
private ListAdapter adapter;
// private LinearLayout linear;
//
// private int stopPosition;
// private int firstViewHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
list = getList();
adapter = new ListAdapter(this, list);
listView.setAdapter(adapter);
listView.setOnScrollListener(this);
listView.setSelection(list.size());
}
/**
* 获取数据
* @return
*/
public List<String getList(){
List<String list = new ArrayList<String ();
for (int i = 0; i < 10; i ) {
list.add(String.valueOf(i));
}
return list;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
/**
* 设置滚动监听,当滚动到第二个时,跳到地list.size() 2个,滚动到倒数第二个时,跳到中间第二个,setSelection时,
* 由于listView滚动并未停止,所以setSelection后会继续滚动,不会出现突然停止的现象
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
/**到顶部添加数据关键代码*/
if (firstVisibleItem <= 2) {
listView.setSelection(list.size() 2);
} else if (firstVisibleItem visibleItemCount adapter.getCount() - 2) {//到底部添加数据
listView.setSelection(firstVisibleItem - list.size());
}
}
}
就是这么简单,嘿嘿,表达能力有点欠缺,不知到你看懂没,没看懂的话,后面附上源码:Android无限循环滚动
以上就是本文的全部内容,希望对大家的学习有所帮助。