listview在第一页时往下拉,没到底部就会刷新,而第二页会拉到底部才会刷新,
到第三页时又会出现没到底部就会刷新了
package com.phone1000.exam01.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.phone1000.exam01.R;
import com.phone1000.exam01.adapter.MyAdapter;
import com.phone1000.exam01.async.DownDataListAsyncTask;
import com.phone1000.exam01.bean.Data;
import com.phone1000.exam01.constant.IMyUrl;
import com.phone1000.exam01.interf.OnGetDownDataListListener;
public class MainActivity extends Activity implements OnGetDownDataListListener {
private ListView lvShow = null;
private TextView noData = null;
private int index = 1;
private boolean isBottom = false;
private MyAdapter adapter = null;
// 全局的数据列表
private List list = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownDataListAsyncTask(MainActivity.this)
.execute(IMyUrl.url + index);
initView();
setListener();
}
private void setListener() {
lvShow.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
/**
* 如果isBottom为true并且手指离开屏幕, 开启新的异步任务,
* 注意:开启异步任务以后要设置isBottom为false 否则,会一直每当
*/
if (isBottom
&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
new DownDataListAsyncTask(MainActivity.this)
.execute(IMyUrl.url + ++index);
isBottom = false;
}
}
// 判断如果first+visible=total则滑到了屏幕底部,则设置isBottom为true;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount) {
// Toast.makeText(
// MainActivity.this,
// "first***" + firstVisibleItem + "visible***"
// + visibleItemCount + "total***"
// + totalItemCount, Toast.LENGTH_LONG).show();
isBottom = true;
}
}
});
}
private void initView() {
lvShow = (ListView) findViewById(R.id.lvShow);
noData = (TextView) findViewById(R.id.NoData);
lvShow.setEmptyView(noData);
adapter = new MyAdapter(this.list, MainActivity.this);
/**
* 在这里设置适配器是只设置了一个适配器,以后到底部刷新时是在此适配器里添加数据
* 如果在回调方法里设置适配器,相当于每次调用回调方法都会给listview重新设置适配器
* 所导致的结果就是每次刷新完,都显示第一页内容
*/
lvShow.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onGetDownDataList(List<Data> list) {
// 每次刷新后在全局的数据列表中添加新获取到的数据
this.list.addAll(list);
// 每次刷新都更新适配器中的数据
adapter.notifyDataSetChanged();
// *****************
// Toast.makeText(MainActivity.this, lvShow.getCount(), Toast.LENGTH_LONG).show();
}
}