其實要達到Android ListView無限循環顯示,主要就是實現繼承Adapter的類。
我這裡用到的是BaseAdapter
- private class MyAdapter extends BaseAdapter{
-
- private Context context;
- private String[] strs = null;
- LayoutInflater inflater = null;
- public MyAdapter(Context context){
- this.context = context;
- //listview中循環顯示的數據
- strs = new String[]{"0","1","2","3","4","5","6","7","8","9"};
- inflater = LayoutInflater.from(context);
- }
- public MyAdapter(){
-
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- //返回int可以保存的最大值,此值為2147483647
- return Integer.MAX_VALUE;
- }
- @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 view, ViewGroup parent) {
- // TODO Auto-generated method stub
- ViewHolder holder = null;
- if(view == null){
- holder = new ViewHolder();
- view = inflater.inflate(R.layout.textview, null);
- holder.text = (TextView) view.findViewById(R.id.text);
- view.setTag(holder);
- }else{
- holder = (ViewHolder) view.getTag();
- }
- //strs[position%strs.length]實現listview中數據的循環
- holder.text.setText(strs[position%strs.length]);
-
- return view;
- }
-
- }
-
- class ViewHolder{
- public TextView text;
- }
在onCreate方法中將adapter賦值給listview
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- listView = (ListView) findViewById(R.id.listview);
- MyAdapter adapter = new MyAdapter(this);
- listView.setAdapter(adapter);
- listView.setSelection(Integer.MAX_VALUE/2+1);
- //設置listview初始化以後的默認選中項,要不然listview初始化以後只能向上拖動而不能向下拖動。
- }
其實,嚴格來說,此程序並不是無限循環,只不過listview內數據太多,達到20多個億,所以也可以算作是無限循環。