Android中动态更新ListView

来源:互联网 发布:魔兽争霸3宽屏mac 编辑:程序博客网 时间:2024/06/05 02:20

在使用ListView时,会遇到当ListView列表滑动到最底端时,添加新的列表项的问题,本文通过代码演示如何动态的添加新的列表项到ListView中。
实现步骤:调用ListView的setOnScrollListener()方法设置滑动监听器,实现OnScrollListener接口的方法,判断当列表滑动到最低端时,加载新的列表项。
其中OnScrollListener接口需要实现如下两个方法:
onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
view 报告滑动状态的视图
firstVisibleItem 可视的第一个列表项的索引
visibleItemCount 可视的列表项个数
totalItemCount 总共的列表项个数
onScrollStateChanged(AbsListView view, int scrollState)
view 报告滑动状态的视图
scrollState 滑动状态
滑动状态包括
SCROLL_STATE_IDLE : 0 视图没有滑动
SCROLL_STATE_TOUCH_SCROLL : 1 用户正在触摸滑动,手指仍在屏幕上
SCROLL_STATE_FLING : 2 用户之前触摸滑动,现在正在滑行,直到停止
下面通过代码给大家演示效果
main.xml

1<?xmlversion="1.0"encoding="utf-8"?>
2<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
3    android:orientation="vertical"
4    android:layout_width="fill_parent"
5    android:layout_height="fill_parent"
6    >
7    <ListView
8        android:id="@id/android:list"
9        android:layout_width="match_parent"
10        android:layout_height="match_parent"
11        android:layout_weight="1"
12        android:drawSelectorOnTop="false"
13        />
14</LinearLayout>

footer.xml

1<?xmlversion="1.0"encoding="utf-8"?>
2<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
3    android:layout_width="fill_parent"
4    android:layout_height="wrap_content"
5    android:gravity="center"
6    android:orientation="horizontal"
7    >
8    <ProgressBar
9        android:id="@+id/progressbar"
10        android:layout_width="wrap_content"
11        android:layout_height="wrap_content"
12        style="\?android:attr/progressBarStyleSmall"
13        />
14    <TextView
15        android:layout_width="wrap_content"
16        android:layout_height="wrap_content"
17        android:textSize="20.0sp"
18        android:text="正在加载..."
19        />
20</LinearLayout>

MainActicity.xml

1packagecom.szy.listview;
2 
3importandroid.app.ListActivity;
4importandroid.os.Bundle;
5importandroid.os.Handler;
6importandroid.os.Message;
7importandroid.view.Gravity;
8importandroid.view.View;
9importandroid.view.ViewGroup;
10importandroid.widget.AbsListView;
11importandroid.widget.BaseAdapter;
12importandroid.widget.ListView;
13importandroid.widget.TextView;
14 
15/**
16 *@author coolszy
17 *@date 2012-3-27
18 *@bloghttp://blog.92coding.com
19 */
20publicclass MainActivity extendsListActivity
21{
22    privateListView mListView;
23    privateCustomAdapter mAdapter;
24    privateint mScrollState;
25    privateView mFooter;
26 
27    @Override
28    publicvoid onCreate(Bundle savedInstanceState)
29    {
30        super.onCreate(savedInstanceState);
31        setContentView(R.layout.main);
32 
33        //获取ListView
34        mListView = getListView();
35        //根据footer.xml描述创建View
36        mFooter = getLayoutInflater().inflate(R.layout.footer, null);
37        // 在ListView底部添加正在加载视图
38        //注意:addFooterView方法需要在调用setListAdapter方法前调用!
39        mListView.addFooterView(mFooter);
40        mAdapter = newCustomAdapter();
41        setListAdapter(mAdapter);
42        //给ListView添加滚动监听器
43        mListView.setOnScrollListener(newAbsListView.OnScrollListener()
44        {
45            @Override
46            publicvoid onScrollStateChanged(AbsListView view, intscrollState)
47            {
48                //记录当前状态
49                mScrollState = scrollState;
50            }
51 
52            @Override
53            publicvoid onScroll(AbsListView view, intfirstVisibleItem, intvisibleItemCount, inttotalItemCount)
54            {
55                // 可视的最后一个列表项的索引
56                intlastVisibleItem = firstVisibleItem + visibleItemCount - 1;
57                //当列表正处于滑动状态且滑动到列表底部时,执行
58                if(mScrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE
59                    && lastVisibleItem == totalItemCount - 1)
60                {
61                    // 执行线程,模拟睡眠5秒钟后添加10个列表项
62                    newThread()
63                    {
64 
65                        privateHandler handler = newHandler()
66                        {
67 
68                            @Override
69                            publicvoid handleMessage(Message msg)
70                            {
71                                super.handleMessage(msg);
72                                //增加Item数量
73                                mAdapter.count += 10;
74                                //通知数据集变化
75                                mAdapter.notifyDataSetChanged();
76                            }
77 
78                        };
79 
80                        @Override
81                        publicvoid run()
82                        {
83                            super.run();
84                            try
85                            {
86                                sleep(5000);
87                                handler.sendEmptyMessage(0);
88                            }catch(InterruptedException e)
89                            {
90                                e.printStackTrace();
91                            }
92                        }
93 
94                    }.start();
95                }
96            }
97        });
98    }
99 
100    privateclass CustomAdapter extendsBaseAdapter
101    {
102        // 初始列表项数量
103        intcount = 20;
104 
105        @Override
106        publicint getCount()
107        {
108            returncount;
109        }
110 
111        @Override
112        publicObject getItem(intposition)
113        {
114            returnposition;
115        }
116 
117        @Override
118        publiclong getItemId(intposition)
119        {
120            returnposition;
121        }
122 
123        @Override
124        publicView getView(intposition, View convertView, ViewGroup parent)
125        {
126            TextView result = (TextView) convertView;
127            //动态创建TextView添加早ListView中
128            if(result == null)
129            {
130                result = newTextView(MainActivity.this);
131                result.setTextAppearance(MainActivity.this, android.R.style.TextAppearance_Large);
132                AbsListView.LayoutParams layoutParams = newAbsListView.LayoutParams
133                                                        (AbsListView.LayoutParams.FILL_PARENT,
134                                                        AbsListView.LayoutParams.WRAP_CONTENT);
135                result.setLayoutParams(layoutParams);
136                result.setGravity(Gravity.CENTER);
137            }
138            result.setText("第 " + (position + 1)+"行");
139            returnresult;
140        }
141    }
142}

效果预览
<a href="http://blog.92coding.com/wp-content/uploads/2012/03/DynamicUpdateListViewDemo.jpg" class="cboxElement" rel="example4" 382"="" style="text-decoration: none; color: rgb(1, 150, 227); ">若水工作室
代码下载:http://115.com/file/bepc3x5d

转载地址:http://blog.92coding.com/index.php/archives/382.html

原创粉丝点击