.Android 分页加载ListView

本文转自:http://www.eoeandroid.com/thread-72987-1-10.html

package eoe.listview;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

private ListView listview;

private ProgressBar loadBar;

private TextView loadText;

private ShopAdapter adapter;

private int start=0;//开始数量

private int limit=3;//每页数量

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

listview=(ListView)findViewById(R.id.main_ListView);

loadBar=(ProgressBar)findViewById(R.id.main_loadBar);

loadText=(TextView)findViewById(R.id.main_loadText);

adapter=new ShopAdapter(this);

listview.setAdapter(adapter);

listview.setOnItemSelectedListener(new OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView arg0, View arg1,

int count, long arg3) {

if(adapter.getCount()==count+1){

loadText.setText("下载中...");

loadBar.setVisibility(View.VISIBLE);


new Thread(mRunnable).start();

}

}

@Override
public void onNothingSelected(AdapterView arg0) {

}

});

new Thread(mRunnable).start();

}

/**

* 商店列表线程

*/

private Runnable mRunnable=new Runnable(){

public void run(){

try {

Thread.sleep(1500);

mHandler.sendMessage(mHandler.obtainMessage());

} catch (InterruptedException e) {

//System.out.println("Error-"+e.getMessage());

}

}

};

Handler mHandler=new Handler(){

public void handleMessage(Message msg){

super.handleMessage(msg);

loadHotShop(limit);

}

};

/**

* 加载店铺

* @return

*/

public void loadHotShop(int limit){

DBLocalService db=new DBLocalService(this);

Cursor cursor=db.querySQL("select * from "+db.TABLE_SHOP+" limit "+start+","+limit,null);

if(cursor.getCount()>0) this.start+=limit;

while(cursor.moveToNext()){

Shop s=new Shop();

s.setId(cursor.getString(cursor.getColumnIndex("id")));

s.setTitle(cursor.getString(cursor.getColumnIndex("title")));

adapter.addShop(s);

}

loadText.setText("");

loadBar.setVisibility(View.GONE);

}

}

 

——————————————————————————————————————————————————————————

 我们第一个应该看见的就是声明了很多私有的变量,因为这样设置就可以变成只能自己来调用了,这样和其它的不发生冲突。其中我们设置了开始数量和每页数量。我们还要new一个adapter=new ShopAdapter(this);这个this就是写的本类,也可以写成类名.this。这个就是看个人的喜好,完事我们开始判断,记住的是,在判断的条件中count是要加1的,这个大家可要记住了我们在写一个run方法,则个就自己来顶了,就不多说了。我们最后写一个loadHotShop()方法,这个方法中要写上你的参数,也就是你想加载几页,就这样,我们分页加载就完成了。要是大家还不懂的话,可以回帖和我交流。要是有更好的方法也可以发帖,分享给大家。

posted @ 2011-11-24 14:45  Glan  阅读(268)  评论(0)    收藏  举报