上拉和下拉刷新列表(自定义listview)
自定义listview:
package cn.net.inch.android.hztour.view;import java.util.Date;import java.util.List;import cn.net.inch.android.hztour.R;//import cn.com.teemax.android.activity.R;//import cn.com.teemax.android.domain.Activity;import android.content.Context;import android.util.AttributeSet;import android.util.Log;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.view.View.MeasureSpec;import android.view.View.OnClickListener;import android.view.animation.LinearInterpolator;import android.view.animation.RotateAnimation;import android.widget.AbsListView;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.Toast;import android.widget.AbsListView.OnScrollListener;import android.widget.ProgressBar;import android.widget.TextView;public class InchListView extends ListView implements OnScrollListener {private static final String TAG = "listview";private final static int RELEASE_To_REFRESH = 0;private final static int PULL_To_REFRESH = 1;private final static int REFRESHING = 2;private final static int DONE = 3;private final static int LOADING = 4;// 实际的padding的距离与界面上偏移距离的比例private final static int RATIO = 3;private LayoutInflater inflater;private View headView;private TextView tipsTextview;private TextView lastUpdatedTextView;private ImageView arrowImageView;private ProgressBar progressBar;private RotateAnimation animation;private RotateAnimation reverseAnimation;// 用于保证startY的值在一个完整的touch事件中只被记录一次private boolean isRecored;private int headContentWidth;private int headContentHeight;private int startY;private int firstItemIndex;private int state;private boolean isBack;private View bottomView;private List adapterlist;private List allList;private int pageSize = 20;private int currentPage = 1;private int totalSize;private BaseAdapter baseAdapter;public void addData(List allList) {int size = pageSize * currentPage;this.allList = allList;totalSize = allList.size();Log.w("totalSize", size + "--" + totalSize);if (totalSize < size) {size = totalSize;}this.adapterlist.addAll(allList.subList((currentPage - 1) * pageSize,size));// handler.sendEmptyMessage(DATA_FINISH);}public void comfirmData(final List allList) {this.getBottomView().setVisibility(View.VISIBLE);this.getBottomView().setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcurrentPage++;addData(allList);if (currentPage * pageSize >= totalSize) {Log.w("--", "bbbb");InchListView.this.removeFooterView(InchListView.this.getBottomView());// listView.getBottomView().setVisibility(View.GONE);}}});// this.getAdapter().}public View getBottomView() {return bottomView;}public void setBottomView(View bottomView) {this.bottomView = bottomView;}private OnRefreshListener refreshListener;private boolean isRefreshable;public InchListView(Context context) {super(context);init(context);}public InchListView(Context context, AttributeSet attrs) {super(context, attrs);init(context);}private void init(Context context) {setCacheColorHint(context.getResources().getColor(R.color.transparent));inflater = LayoutInflater.from(context);headView = (LinearLayout) inflater.inflate(R.layout.head, null);arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView);arrowImageView.setMinimumWidth(70);arrowImageView.setMinimumHeight(50);progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView);measureView(headView);headContentHeight = headView.getMeasuredHeight();headContentWidth = headView.getMeasuredWidth();headView.setPadding(0, -1 * headContentHeight, 0, 0);headView.invalidate();Log.v("size", "width:" + headContentWidth + " height:"+ headContentHeight);addHeaderView(headView, null, false);setOnScrollListener(this);animation = new RotateAnimation(0, -180,RotateAnimation.RELATIVE_TO_SELF, 0.5f,RotateAnimation.RELATIVE_TO_SELF, 0.5f);animation.setInterpolator(new LinearInterpolator());animation.setDuration(250);animation.setFillAfter(true);reverseAnimation = new RotateAnimation(-180, 0,RotateAnimation.RELATIVE_TO_SELF, 0.5f,RotateAnimation.RELATIVE_TO_SELF, 0.5f);reverseAnimation.setInterpolator(new LinearInterpolator());reverseAnimation.setDuration(200);reverseAnimation.setFillAfter(true);state = DONE;isRefreshable = false;/** * 加载更多按钮 * * */bottomView = inflater.inflate(R.layout.load_more, null);bottomView.setVisibility(View.GONE);this.addFooterView(bottomView);}@Overridepublic void setAdapter(ListAdapter adapter) {// TODO Auto-generated method stubsuper.setAdapter(adapter);}public void onScrollStateChanged(AbsListView view, int scrollState) {int itemsLastIndex = getAdapter().getCount() - 1; // 数据集最后一项的索引int lastIndex = itemsLastIndex + 1;Log.w("加载更多", visibleLastIndex+"---"+lastIndex+"-"+totalSize);if (scrollState == OnScrollListener.SCROLL_STATE_IDLE&& visibleLastIndex == lastIndex&&totalSize+1>lastIndex) {Log.w("===========", "加载更多");currentPage++;addData(allList);comfirmData(allList);if (currentPage * pageSize >= totalSize) {Log.w("--", "bbbb");InchListView.this.removeFooterView(InchListView.this.getBottomView());// listView.getBottomView().setVisibility(View.GONE);}baseAdapter.notifyDataSetChanged();//((BaseAdapter)this.getAdapter()).notifyDataSetChanged();// 如果是自动加载,可以在这里放置异步加载数据的代码}}private int visibleLastIndex = 0;private int visibleItemCount;@Overridepublic void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {firstItemIndex = firstVisibleItem;this.visibleItemCount = visibleItemCount;visibleLastIndex = firstVisibleItem + visibleItemCount;Log.e("========================= ", "========================");// 如果所有的记录选项等于数据集的条数,则移除列表底部视图}public boolean onTouchEvent(MotionEvent event) {if (isRefreshable) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:if (firstItemIndex == 0 && !isRecored) {isRecored = true;startY = (int) event.getY();Log.v(TAG, "在down时候记录当前位置‘");}break;case MotionEvent.ACTION_UP:if (state != REFRESHING && state != LOADING) {if (state == DONE) {// 什么都不做}if (state == PULL_To_REFRESH) {state = DONE;changeHeaderViewByState();Log.v(TAG, "由下拉刷新状态,到done状态");}if (state == RELEASE_To_REFRESH) {state = REFRESHING;changeHeaderViewByState();onRefresh();Log.v(TAG, "由松开刷新状态,到done状态");}}isRecored = false;isBack = false;break;case MotionEvent.ACTION_MOVE:int tempY = (int) event.getY();if (!isRecored && firstItemIndex == 0) {Log.v(TAG, "在move时候记录下位置");isRecored = true;startY = tempY;}if (state != REFRESHING && isRecored && state != LOADING) {// 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动// 可以松手去刷新了if (state == RELEASE_To_REFRESH) {setSelection(0);// 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步if (((tempY - startY) / RATIO < headContentHeight)&& (tempY - startY) > 0) {state = PULL_To_REFRESH;changeHeaderViewByState();Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");}// 一下子推到顶了else if (tempY - startY <= 0) {state = DONE;changeHeaderViewByState();Log.v(TAG, "由松开刷新状态转变到done状态");}// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步else {// 不用进行特别的操作,只用更新paddingTop的值就行了}}// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态if (state == PULL_To_REFRESH) {setSelection(0);// 下拉到可以进入RELEASE_TO_REFRESH的状态if ((tempY - startY) / RATIO >= headContentHeight) {state = RELEASE_To_REFRESH;isBack = true;changeHeaderViewByState();Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");}// 上推到顶了else if (tempY - startY <= 0) {state = DONE;changeHeaderViewByState();Log.v(TAG, "由DOne或者下拉刷新状态转变到done状态");}}// done状态下if (state == DONE) {if (tempY - startY > 0) {state = PULL_To_REFRESH;changeHeaderViewByState();}}// 更新headView的sizeif (state == PULL_To_REFRESH) {headView.setPadding(0, -1 * headContentHeight+ (tempY - startY) / RATIO, 0, 0);}// 更新headView的paddingTopif (state == RELEASE_To_REFRESH) {headView.setPadding(0, (tempY - startY) / RATIO- headContentHeight, 0, 0);}}break;}}return super.onTouchEvent(event);}// 当状态改变时候,调用该方法,以更新界面private void changeHeaderViewByState() {switch (state) {case RELEASE_To_REFRESH:arrowImageView.setVisibility(View.VISIBLE);progressBar.setVisibility(View.GONE);tipsTextview.setVisibility(View.VISIBLE);lastUpdatedTextView.setVisibility(View.VISIBLE);arrowImageView.clearAnimation();arrowImageView.startAnimation(animation);tipsTextview.setText("松开刷新");Log.v(TAG, "当前状态,松开刷新");break;case PULL_To_REFRESH:progressBar.setVisibility(View.GONE);tipsTextview.setVisibility(View.VISIBLE);lastUpdatedTextView.setVisibility(View.VISIBLE);arrowImageView.clearAnimation();arrowImageView.setVisibility(View.VISIBLE);// 是由RELEASE_To_REFRESH状态转变来的if (isBack) {isBack = false;arrowImageView.clearAnimation();arrowImageView.startAnimation(reverseAnimation);tipsTextview.setText("下拉刷新");} else {tipsTextview.setText("下拉刷新");}Log.v(TAG, "当前状态,下拉刷新");break;case REFRESHING:headView.setPadding(0, 0, 0, 0);progressBar.setVisibility(View.VISIBLE);arrowImageView.clearAnimation();arrowImageView.setVisibility(View.GONE);tipsTextview.setText("正在刷新...");lastUpdatedTextView.setVisibility(View.VISIBLE);Log.v(TAG, "当前状态,正在刷新...");break;case DONE:headView.setPadding(0, -1 * headContentHeight, 0, 0);progressBar.setVisibility(View.GONE);arrowImageView.clearAnimation();arrowImageView.setImageResource(R.drawable.arrow3);tipsTextview.setText("下拉刷新");lastUpdatedTextView.setVisibility(View.VISIBLE);Log.v(TAG, "当前状态,done");break;}}public void setonRefreshListener(OnRefreshListener refreshListener) {this.refreshListener = refreshListener;isRefreshable = true;}public interface OnRefreshListener {public void onRefresh();}public void onRefreshComplete() {state = DONE;lastUpdatedTextView.setText("最近更新:" + new Date().toLocaleString());changeHeaderViewByState();}private void onRefresh() {if (refreshListener != null) {refreshListener.onRefresh();}}// 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及heightprivate void measureView(View child) {ViewGroup.LayoutParams p = child.getLayoutParams();if (p == null) {p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);}int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);int lpHeight = p.height;int childHeightSpec;if (lpHeight > 0) {childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,MeasureSpec.EXACTLY);} else {childHeightSpec = MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED);}child.measure(childWidthSpec, childHeightSpec);}public void setAdapter(BaseAdapter adapter) {lastUpdatedTextView.setText("最近更新:" + new Date().toLocaleString());super.setAdapter(adapter);}public void setAdapterlist(List adapterlist) {this.adapterlist = adapterlist;}public List getAdapterlist() {return adapterlist;}public void setPageSize(int pageSize) {this.pageSize = pageSize;}public int getPageSize() {return pageSize;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public int getCurrentPage() {return currentPage;}public void setTotalSize(int totalSize) {this.totalSize = totalSize;}public int getTotalSize() {return totalSize;}public void setBaseAdapter(BaseAdapter baseAdapter,List aList) {this.setAdapter(baseAdapter);this.setAdapterlist(aList);this.baseAdapter = baseAdapter;}public BaseAdapter getBaseAdapter() {return baseAdapter;}}
在activity使用:
/** * 景点列表 */package cn.net.inch.android.hztour;import java.text.Collator;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Locale;import org.apache.commons.httpclient.HostConfiguration;import com.tencent.weibo.api.Private_API;import android.R.bool;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.content.Intent;import android.content.res.ColorStateList;import android.graphics.Color;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.AsyncTask;import android.os.Bundle;import android.os.Message;import android.util.Log;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.Window;import android.view.View.OnClickListener;import android.widget.AbsListView;import android.widget.AdapterView;import android.widget.AutoCompleteTextView;import android.widget.Button;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;import android.widget.AbsListView.OnScrollListener;import android.widget.AdapterView.OnItemClickListener;import cn.net.inch.android.hztour.adapter.ScenicSpotAdapter;import cn.net.inch.android.hztour.common.DBException;import cn.net.inch.android.hztour.common.HztourConstant;import cn.net.inch.android.hztour.common.InchHandler;import cn.net.inch.android.hztour.common.StringUtil;import cn.net.inch.android.hztour.dao.DaoFactory;import cn.net.inch.android.hztour.domain.Hotspot;import cn.net.inch.android.hztour.view.InchListView;import cn.net.inch.android.hztour.view.MyListView;import cn.net.inch.android.hztour.view.MyListView.OnRefreshListener;import cn.net.inch.android.hztour.webapi.TravelDataApi;public class HotspotListActivity extends Activity implements OnClickListener {List<Hotspot> hoList = new ArrayList<Hotspot>();List<Hotspot> hotsList_list = new ArrayList<Hotspot>();List<Hotspot> tempList = new ArrayList<Hotspot>();List<Button> listButton = null;// private ListView listView;private TextView titleView;private View loadMoreView;private View progressBarView;private Long idLong;private String test;private String channelTemp;private Long zhixu_id;private AutoCompleteTextView autoComp;// private List<Hotspot> hotshList;private LinearLayout linearLayout, Linear_scenic_button;private Button blackButton, rightButton, scenicButton, searchButton,loadMoreButton;private String channelCode;private String titleName;private Button byDistanceBt, byHostBt, bySpellBt;private ProgressBar progressBar;private Location location;private ScenicSpotAdapter listViewAdater = null;private final static int DATA_SUCCESS = 0x111;private final static int DATA_FAIL = 0x112;private final static int LOCATION_FIN = 0x113;private final static int DATA_SEARCH_SUCCESS = 0x114;private final static int DATA_LOAD_MORE = 0x115;private final static int PROBAR_HIDDEN = 0x116;private TravelDataApi tDataApi;private int sortType;private List<Hotspot> hostList;private List<String> pList = new ArrayList<String>();TravelDataApi travelDataApi = new TravelDataApi();// <<<<<<< .mineprivate ProgressDialog progressDialog = null;private int currentPage = 1; // 当前页,默认为1// private int pageSize = 10; // 每页显示十条信息private int last_item_position; // 最后item的位置private boolean isLoading = false; // 是否加载过,控制加载次数private int datasize = 38; private int pageSta = 0;private static final int SIZEPAGE = 20;private static int pageSize = SIZEPAGE;private int visibleLastIndex;//private MyListView listView;private InchListView listView;// =======// >>>>>>> .r18731private InchHandler handler = new InchHandler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubswitch (msg.what) {case DATA_SUCCESS:listView.comfirmData(hostList); //用到listveiw自定义comfirmData方法listViewAdater.notifyDataSetChanged();progressBarView.setVisibility(View.INVISIBLE);// progressDialog.dismiss();// =======if (hoList != null && hoList.size() > 0) {try {DaoFactory.getHotspotDao().addHotspot(hoList);Log.w("save", "-------------------");} catch (DBException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// >>>>>>> .r18731break;case DATA_FAIL:Toast.makeText(HotspotListActivity.this, "服务端数据更新失败,请稍后再试!",Toast.LENGTH_LONG).show();break;case LOCATION_FIN:break; case DATA_LOAD_MORE: listView.removeFooterView(loadMoreView);// Toast.makeText(HotspotListActivity.this, "数据加载完成", Toast.LENGTH_LONG).show(); break;case PROBAR_HIDDEN:listViewAdater.notifyDataSetChanged();progressBarView.setVisibility(View.INVISIBLE);Boolean isAdd = (Boolean)msg.obj;addOrRefreshByCondition(isAdd);break;default:break;}super.handleMessage(msg);}};private LocationManager locationManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);this.requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.scenic_spot);// progressBar = (ProgressBar) findViewById(R.id.circleProgressBar);//progressBar = (ProgressBar) findViewById(R.id.scenic_circleProgressBar);//if (null != progressBar) {//progressBar.setIndeterminate(false);//progressBar.setVisibility(View.VISIBLE);//}progressBarView = findViewById(R.id.ProgessBar_layout);if (null != progressBarView) {progressBarView.setVisibility(View.VISIBLE);}byDistanceBt = (Button) findViewById(R.id.distance_sort_button_id);byHostBt = (Button) findViewById(R.id.host_sort_button_id);bySpellBt = (Button) findViewById(R.id.spell_sort_button_id);byDistanceBt.setTextColor(R.color.ivory);byDistanceBt.setOnClickListener(this);byHostBt.setOnClickListener(this);bySpellBt.setOnClickListener(this);//listView = (MyListView) findViewById(R.id.scenic_list_id);listView = (InchListView)findViewById(R.id.scenic_list_id);loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);//listView.addFooterView(loadMoreView); // 把view添加到列表的底部//loadMoreButton = (Button) loadMoreView//.findViewById(R.id.loadMoreButton);//loadMoreButton.setVisibility(View.VISIBLE);//loadMoreButton.setOnClickListener(new View.OnClickListener() {////@Override//public void onClick(View v) {//// TODO Auto-generated method stub----//loadMoreButton.setText("正在加载中...");//handler.postDelayed(new Runnable() {////@Override//public void run() {//// TODO Auto-generated method stub// addItem(tempList); //点击更多开始加载余下的数据// loadMoreButton.setText("查看更多...");//}////}, 1000);//}////});init();initData();// setProgressBarIndeterminateVisibility(true);// Toast.makeText(HotspotListInforActivity.this, "aaa",// Toast.LENGTH_LONG).show();}private void init() {linearLayout = (LinearLayout) findViewById(R.id.linear2_id);Linear_scenic_button = (LinearLayout) findViewById(R.id.Linear_scenic_button_id);// listView = (ListView) findViewById(R.id.scenic_list_id);listViewAdater = new ScenicSpotAdapter(this,hoList,pList,listView);//listView.setAdapter(listViewAdater);listView.setBaseAdapter(listViewAdater, hoList);listButton = new ArrayList<Button>();// listView.setPadding(20, 20, 20, 100);//listViewAdater = new ScenicSpotAdapter(this, hoList, pList);//listView.setAdapter(listViewAdater);// MyListView myListView = new MyListView(this);/** * listview下拉刷新,类似于新浪微薄 */listView.setonRefreshListener(new InchListView.OnRefreshListener() {public void onRefresh() {new AsyncTask<Void, Void, Void>() {protected Void doInBackground(Void... params) {try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}//hoList.addAll(tempList);return null;}@Overrideprotected void onPostExecute(Void result) {listViewAdater.notifyDataSetChanged();listView.onRefreshComplete();}}.execute(null);}});listView.setOnItemClickListener(new MyHotspotListListener());blackButton = (Button) findViewById(R.id.module_top_left);blackButton.setOnClickListener(this);rightButton = (Button) findViewById(R.id.module_top_right);rightButton.setOnClickListener(this);rightButton.setVisibility(View.VISIBLE);rightButton.setBackgroundResource(R.drawable.sort_btn_select);scenicButton = (Button) findViewById(R.id.scenic_right_button);scenicButton.setOnClickListener(this);scenicButton.setVisibility(View.VISIBLE);scenicButton.setBackgroundResource(R.drawable.seach2);channelCode = getIntent().getExtras().getString("channelCode");Log.v("channelCode=====-------------", channelCode);if (channelCode.equals(HztourConstant.XINGJIJIUDIAN)) {Log.v("+++++++++++------------", "+++++++++++++++");byHostBt.setBackgroundResource(R.drawable.star_selected_5);byDistanceBt.setBackgroundResource(R.drawable.start_4);bySpellBt.setBackgroundResource(R.drawable.star_3);byHostBt.setText("三级酒店");byHostBt.setTextColor(Color.BLACK);byDistanceBt.setText("四级酒店");byDistanceBt.setTextColor(Color.WHITE);bySpellBt.setText("五级酒店");bySpellBt.setTextColor(Color.WHITE);byHostBt.setOnClickListener(listener);byDistanceBt.setOnClickListener(listener);bySpellBt.setOnClickListener(listener);}searchButton = (Button) findViewById(R.id.search_content_button);searchButton.setOnClickListener(this);// listButton.add(byDistanceBt);// listButton.add(byHostBt);// listButton.add(bySpellBt);autoComp = (AutoCompleteTextView) findViewById(R.id.search_autoCompete);titleView = (TextView) findViewById(R.id.module_top_title);titleName = getIntent().getExtras().getString("hotspot_titleName");idLong = getIntent().getLongExtra("distrid", 0);Log.v("idLong", idLong + "");zhixu_id = getIntent().getLongExtra("zhixu_id", 0);channelTemp = getIntent().getStringExtra("channelName");Log.v("channelTemp", channelTemp+"");if (titleName != null && !titleName.equals("")) {titleView.setText(titleName); // 设置标题}// progressDialog = ProgressDialog.show(HotspotListActivity.this,// "加载中...", "请稍后", true, false);}//// 点击更多加载新数据//public void addItem(List<Hotspot> hostList) {//Log.v("hostList_........", hostList.size()+"");//pageSta = 0;//pageSize += SIZEPAGE;//int spageSize = pageSize;//if (pageSize > hostList.size()) { //pageSize = hostList.size(); //}//Log.w("pageSize", pageSize + "--" + spageSize + "hotspotsize"//+ hostList.size());//hoList.addAll(hostList.subList(spageSize - SIZEPAGE, pageSize)); //从第20条下面开始取//Log.w("pageSize", spageSize + "");//listViewAdater.notifyDataSetChanged();//}/** * 控制按钮颜色 * * @param button */// public void selectButton(Button button) {// for (Button button2 : listButton) {// button2.setBackgroundResource(R.drawable.cell_sort_hot_select_img);// button2.se// }// button.setBackgroundResource(R.drawable.cell_sort_distance_select_img);// }/** * 从数据库取得景点列表的数据并添加到hoList和hotsList_list中 */public void refreshDataDb(String channelCode) {// List<Hotspot> tempList = new ArrayList<Hotspot>();try {Boolean isAdd = false;hostList = DaoFactory.getHotspotDao().getListByChannelCode(channelCode);if (hostList != null && !hostList.isEmpty()) {tempList.addAll(hostList);addData(hostList); Message message = handler.obtainMessage();message.what = PROBAR_HIDDEN;message.obj = !isAdd;handler.sendMessage(message);//hoList.clear();//hoList.addAll(hostList);//hotsList_list.clear();//hotsList_list.addAll(hostList);//handler.sendEmptyMessage(DATA_SUCCESS);}} catch (DBException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private void addOrRefreshByCondition(Boolean isAdd) {if (isAdd) {//addHotspot(tempList);}else {refreshHotspot(tempList);}}/** * 第一次获取数据 * @param hotspotList *///private void addHotspot(final List<Hotspot> hotspotList) {//deleteItem();////listView.removeFooterView(loadMoreView);//pageSize = SIZEPAGE;//if (pageSize > hotspotList.size()) {//pageSize = hotspotList.size(); //取出的小于20,把底部除//listView.removeFooterView(loadMoreView);//}else {//listView.addFooterView(loadMoreView); //如果取出来的数据大于20条,则在底部添加更多按钮用来刷新剩下的数据//}//hoList.addAll(hotspotList.subList(0, pageSize)); //取0到19//////progressBar.setVisibility(View.GONE);///**// * 列表// *///listView.setOnScrollListener(new AbsListView.OnScrollListener() {////@Override//public void onScroll(AbsListView view, int firstVisibleItem,//int visibleItemCount, int totalItemCount) {//// TODO Auto-generated method stub//visibleLastIndex = firstVisibleItem + visibleItemCount;//Log.w("totalItemCount", totalItemCount + "=="//+ hotspotList.size());//if (totalItemCount == hotspotList.size() + 1) {////Toast.makeText(HotspotListActivity.this, "数据全部加载完!",////Toast.LENGTH_SHORT).show();//listView.removeFooterView(loadMoreView);//}////}////@Override//public void onScrollStateChanged(AbsListView view, int scrollState) {//// TODO Auto-generated method stub////// 滑到底部后自动加载,判断listview已经停止滚动并且最后可视的条目等于adapter的条目//if (scrollState == OnScrollListener.SCROLL_STATE_IDLE////&& visibleLastIndex == view.getCount()) {//// 如果是自动加载,可以在这里放置异步加载数据的代码////loadMoreView.setVisibility(View.VISIBLE);//loadMoreButton.setText("正在加载中..."); // 设置按钮文字//handler.postDelayed(new Runnable() {////@Override//public void run() {//addItem(hotspotList);//loadMoreButton.setText("查看更多..."); // 恢复按钮文字//handler.sendEmptyMessage(DATA_LOAD_MORE);//}//}, 1000);//}////}////});//}public void refreshHotspot(List<Hotspot> hotspotList) {deleteItem();listView.removeFooterView(loadMoreView);pageSize = SIZEPAGE;if (pageSize > hotspotList.size()) {pageSize = hotspotList.size();} else {listView.addFooterView(loadMoreView);}hoList.addAll(hotspotList.subList(0, pageSize));listViewAdater.notifyDataSetChanged();}private void deleteItem() {hoList.clear();}private void initData() {new Thread() {public void run() {if (channelCode != null && !channelCode.equals("")) {/** * 先去数据库缓存数据 * */refreshDataDb(channelCode);/** * 网络交互 重新比对数据 * * */hostList = null;if (idLong != null && idLong > 0) {//获取周边旅游列表hostList = travelDataApi.ListCirHotspot(channelCode,idLong, "", HotspotListActivity.this, handler);if (hostList != null && !hostList.isEmpty()) {hoList.clear();//hoList.addAll(hostList);handler.sendEmptyMessage(DATA_SUCCESS);}} else if (idLong == 0) {//从后台获取景点列表信息hostList = travelDataApi.ListHotspot(channelCode, "",HotspotListActivity.this, handler);if (hostList != null) {try {//将后台取得景点列表数据保存数据库中DaoFactory.getHotspotDao().addHotspot(hostList);refreshDataDb(channelCode);//handler.sendEmptyMessage(DATA_SUCCESS);} catch (DBException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}else {String keyStr = getIntent().getExtras().getString("keyStr");tDataApi = new TravelDataApi();List<Hotspot> hostList = null;hostList = tDataApi.HotspotFind(keyStr,HotspotListActivity.this, handler);if (hostList != null && !hostList.isEmpty()) {hoList.clear();hoList.addAll(hostList);handler.sendEmptyMessage(DATA_SUCCESS);} else {handler.sendEmptyMessage(DATA_FAIL);}//}}}.start();}private void addData(List<Hotspot> temphoList) {listView.addData(temphoList); //用到listveiw自定义addData方法handler.sendEmptyMessage(DATA_SUCCESS);}/** * 对星级酒店按钮控制 */private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.host_sort_button_id:byHostBt.setBackgroundResource(R.drawable.star_selected_5);byDistanceBt.setBackgroundResource(R.drawable.start_4);bySpellBt.setBackgroundResource(R.drawable.star_3);byHostBt.setTextColor(Color.BLACK);byDistanceBt.setTextColor(Color.WHITE);bySpellBt.setTextColor(Color.WHITE);filterByLve(HztourConstant.LEV_3);break;case R.id.distance_sort_button_id:byDistanceBt.setBackgroundResource(R.drawable.start_selected_4);byHostBt.setBackgroundResource(R.drawable.star_5);bySpellBt.setBackgroundResource(R.drawable.star_3);byDistanceBt.setTextColor(Color.BLACK);byHostBt.setTextColor(Color.WHITE);bySpellBt.setTextColor(Color.WHITE);filterByLve(HztourConstant.LEV_4);break;case R.id.spell_sort_button_id:bySpellBt.setBackgroundResource(R.drawable.start_selected_3);byDistanceBt.setBackgroundResource(R.drawable.start_4);byHostBt.setBackgroundResource(R.drawable.star_5);bySpellBt.setTextColor(Color.BLACK);byDistanceBt.setTextColor(Color.WHITE);byHostBt.setTextColor(Color.WHITE);filterByLve(HztourConstant.LEV_5);break;default:break;}}};// private void byLveSort(final List<Hotspot> hList, final String lve) {// Collections.sort(hList, new Comparator() {// public int compare(Object object1, Object object2) {// Hotspot ob1 = (Hotspot) object1;// Hotspot ob2 = (Hotspot) object2;//// String lve1 = ob1.getLve();// String lve2 = ob2.getLve();//// if (Integer.parseInt(lve1) > Integer.parseInt(lve2)// && lve.equals(HztourConstant.LEV_5)) {// Log.v("lve1======", lve1);// Log.v("lve2======", lve2);// return 1;// } else if (Integer.parseInt(lve1) < Integer.parseInt(lve2)// && lve.equals(HztourConstant.LEV_4)) {// Log.v("lve3======", lve1);// Log.v("lve4======", lve2);// return -1;// } else {// return 0;// }// }// });// pList.clear();// listViewAdater.notifyDataSetChanged();// }class MyHotspotListListener implements OnItemClickListener {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {// TODO Auto-generated method stub// Toast.makeText(HotspotListActivity.this,"",// Toast.LENGTH_LONG).show();Log.v("arg2", arg2-1 +"");Hotspot hotspot = hoList.get(arg2-1);int value = hotspot.getId();long districtId = hotspot.getDistrictId();Log.v("districtId------", districtId + "");String hotspot_infor_titleName = hoList.get(arg2-1).getName();Log.v("values===============", value + ""+ hotspot_infor_titleName);if (value > 0) {Intent intent = new Intent(HotspotListActivity.this,HotspotListInforActivity.class);intent.putExtra("values", value);intent.putExtra("hotspot_infor_titleName",hotspot_infor_titleName);intent.putExtra("channel_name", titleName);intent.putExtra("zbzhusu", channelCode);intent.putExtra("channeltemp", channelTemp); startActivity(intent);}}}private double rad(double d) {return d * Math.PI / 180.0;}private static final double EARTH_RADIUS = 6378.137;public double GetDistance(double lat1, double lng1, double lat2, double lng2) {double radLat1 = rad(lat1);double radLat2 = rad(lat2);double a = radLat1 - radLat2;double b = rad(lng1) - rad(lng2);double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)+ Math.cos(radLat1) * Math.cos(radLat2)* Math.pow(Math.sin(b / 2), 2)));s = s * EARTH_RADIUS;// s = Math.round(s * 10000) / 10000;// Log.w("", msg)return s;}public void setDistance(List<Hotspot> hotspotList, Location location) {Double compareDistance = null;// nearHots = 0;if (hotspotList != null) {for (Hotspot hotspot : hotspotList) {if (hotspot.getLat() != null && hotspot.getLon() != null) {compareDistance = GetDistance(hotspot.getLat(), hotspot.getLon(), location.getLatitude(), location.getLongitude());hotspot.setDistance(compareDistance);// Log.w("comapre", compareDistance + "");}}}}public void initGps() {String serviceName = Context.LOCATION_SERVICE;locationManager = (LocationManager) getSystemService(serviceName);location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);Location gpsLocation;gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);if (gpsLocation != null) {location = gpsLocation;}// locationManager.requestLocationUpdates(// LocationManager.NETWORK_PROVIDER, 0, 0, myLocationListener);/** *开启GPS监听 * * */if (location == null) {locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2,new LocationListener() {@Overridepublic void onLocationChanged(Location location) {// TODO Auto-generated method stubHotspotListActivity.this.location = location;handler.sendEmptyMessage(LOCATION_FIN);locationManager.removeUpdates(this);}@Overridepublic void onProviderDisabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onProviderEnabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onStatusChanged(String provider,int status, Bundle extras) {// TODO Auto-generated method stub}});}}public void sortByDistance(List<Hotspot> hList) {setDistance(hList, location);sortType = Hotspot.sort_distance;Collections.sort(hList, new Comparator() {public int compare(Object object1, Object object2) {Hotspot ob1 = (Hotspot) object1;Hotspot ob2 = (Hotspot) object2;if (ob1.getDistance() > ob2.getDistance()) {return 1;} else if (ob1.getDistance() < ob2.getDistance()) {return -1;} else {return 0;}}});pList.clear();// listViewAdater = new ScenicSpotAdapter(this, hoList, pList);//refreshHotspot(tempList);listViewAdater.notifyDataSetChanged();}public void sortByHotspot(List<Hotspot> hList) {sortType = Hotspot.sort_hot;Collections.sort(hList, new Comparator() {public int compare(Object object1, Object object2) {Hotspot ob1 = (Hotspot) object1;Hotspot ob2 = (Hotspot) object2;if (ob1.getRecomeIndex() > ob2.getRecomeIndex()) {return 1;} else if (ob1.getRecomeIndex() < ob2.getRecomeIndex()) {return -1;} else {return 0;}}});pList.clear();//refreshHotspot(tempList);// listViewAdater = new ScenicSpotAdapter(this, hoList, pList);listViewAdater.notifyDataSetChanged();}public void sortByPinyin(List<Hotspot> hList) {final Comparator comparator = Collator.getInstance(Locale.CHINA);sortType = Hotspot.sort_pinyin;Collections.sort(hList, new Comparator() {@Overridepublic int compare(Object lhs, Object rhs) {// TODO Auto-generated method stubHotspot ob1 = (Hotspot) lhs;Hotspot ob2 = (Hotspot) rhs;return comparator.compare(ob1.getName(), ob2.getName());}});/** * * 获取拼音首字母 * */String pSt;String tempString = null;for (Hotspot hotspot : hList) {pSt = hotspot.getName().substring(0, 1);Log.w("ff", pSt);pSt = StringUtil.String2Alpha(pSt);Log.d("ffdd", pSt);if (tempString == null|| (tempString != null && !pSt.equals(tempString))) {// hotspot.setPinyin(pSt);pList.add(pSt);tempString = pSt;Log.i("fs", pSt);} else {pList.add("");}}//refreshHotspot(tempList);// listViewAdater = new ScenicSpotAdapter(this, hoList, pList);listViewAdater.notifyDataSetChanged();}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.module_top_left:finish();break;case R.id.distance_sort_button_id:Toast.makeText(HotspotListActivity.this, "正在定位当前位置...",Toast.LENGTH_LONG).show();initGps();if (location != null && hoList != null) {sortByDistance(hoList);}byDistanceBt.setBackgroundResource(R.drawable.cell_sort_distance_select_img);byHostBt.setBackgroundResource(R.drawable.cell_sort_hot_select_img);bySpellBt.setBackgroundResource(R.drawable.cell_sort_spell_select_img);// byDistanceBt.setFocusable(trt)break;case R.id.host_sort_button_id:byHostBt.setBackgroundResource(R.drawable.cell_sort_hot_img);byDistanceBt.setBackgroundResource(R.drawable.cell_sort_distance_img);bySpellBt.setBackgroundResource(R.drawable.cell_sort_spell_select_img);sortByHotspot(hoList);break;case R.id.spell_sort_button_id://pageSize = SIZEPAGE;//deleteItem();bySpellBt.setBackgroundResource(R.drawable.cell_sort_spell_img);byDistanceBt.setBackgroundResource(R.drawable.cell_sort_distance_img);byHostBt.setBackgroundResource(R.drawable.cell_sort_hot_select_img);sortByPinyin(hoList);//refreshHotspot(tempList);break;case R.id.scenic_right_button:linearLayout.setVisibility(View.VISIBLE);Linear_scenic_button.setVisibility(View.GONE);break;case R.id.module_top_right:// Toast.makeText(HotspotListActivity.this, "aaa",// Toast.LENGTH_LONG).show();linearLayout.setVisibility(View.GONE);Linear_scenic_button.setVisibility(View.VISIBLE);break;case R.id.search_content_button:String searchStr = autoComp.getText().toString();searchHotspot(searchStr);// hoList = searchHotspot(autoComp.getText().toString());// if (hoList != null ) {// if (hoList.size() == 0) {// Toast.makeText(this, "有你所搜索的内容", Toast.LENGTH_LONG).show();// }// refreshHotspot(hoList);// }break;default:break;}}/** * 景点搜索 * * @param keyWord */public void searchHotspot(String keyWord) {// keyWord = keyWord.trim();List<Hotspot> tempList = new ArrayList<Hotspot>();for (Hotspot hotspot : hoList) {if (hotspot.getName().contains(keyWord)) {tempList.add(hotspot);}}hoList.clear();hoList.addAll(tempList);listViewAdater.notifyDataSetChanged();}/** * 对酒店星级过滤 * * @param lveType */private void filterByLve(String lveType) {if (tempList != null && tempList.size() > 0) {hoList.clear();for (Hotspot hotspot : tempList) {Log.w("lve", lveType + "--" + hotspot.getLve());if (hotspot.getLve() != null&& hotspot.getLve().equals(lveType)) {Log.w("lve+++++++++++", lveType + "");hoList.add(hotspot);}}listViewAdater.notifyDataSetChanged();} else {Log.w("hotspotList", "null");}}//@Override//public void onScroll(AbsListView view, int firstVisibleItem,//int visibleItemCount, int totalItemCount) {//// TODO Auto-generated method stub////// Log.w("totalItemCount", totalItemCount + "=="//// + NoteListActivity.this.hotspots.size());//try {//visibleLastIndex = firstVisibleItem + visibleItemCount;//Log.v("visibleLastIndex", visibleLastIndex + "");//if (null != hostList) {//// Log.w("热点size" + hostList.size()+"," + "总的size"//// + totalItemCount+"");//Log.w("hostList_size" + hostList.size(), "总的size"//+ totalItemCount);//if (totalItemCount == hostList.size() + 1) {////Toast.makeText(HotspotListActivity.this, "数据全部加载完",//Toast.LENGTH_LONG).show();//listView.removeFooterView(loadMoreView);//}//}//} catch (Exception e) {//e.printStackTrace();//}////}////@Override//public void onScrollStateChanged(AbsListView view, int scrollState) {//// TODO Auto-generated method stub////Log.w("scrollState", "fling---------" // 开始滚动状态//+ OnScrollListener.SCROLL_STATE_FLING);//Log.w("scrollState", "idle----------"//+ OnScrollListener.SCROLL_STATE_IDLE); // 滚动停止状态//Log.w("scrollState", "touchScroll---"//+ OnScrollListener.SCROLL_STATE_TOUCH_SCROLL); // 正在滚动//Log.w("scrollState", "current-------" + scrollState);//Log.w("index", visibleLastIndex + "-----" + view.getCount());////Log.w("mmmmmmmm--------", view.getChildCount() + "");//// 当滚到最后一行且停止滚动时,执行加载//if ((scrollState == OnScrollListener.SCROLL_STATE_IDLE)//&& visibleLastIndex == view.getCount()) {//// 如果是自动加载,可以在这里放置异步加载数据的代码//if (loadMoreButton != null) {////loadMoreButton.setText("正在加载中..."); // 设置按钮文字//}////addItem();//}////}// private List<String> list = new ArrayList<String>();// private List<Object> temp = new ArrayList<Object>();// private String lveString;// public void byLveSort() {//// Hotspot h = new Hotspot();// //// for (Hotspot hotspot2 : hoList) {// Log.v("lve", hotspot2.getLve());// lveString = hotspot2.getLve();// temp.add(lveString);// }// for (int i = 0; i < hoList.size(); i++) {// String byLve = hoList.get(i).getLve();// // hotspot.setLve(byLve);// if (byLve.equals(HztourConstant.LEV_3)) {// // list.add(byLve);// temp.add(hotspot);//// } else if (byLve.equals(HztourConstant.LEV_4)) {// temp.add(hotspot);// } else if(byLve.equals(HztourConstant.LEV_5)){// temp.add(hotspot);// }// hoList.addAll(temp);// handler.sendEmptyMessage(DATA_SUCCESS);// }// private String byLve;//// public void byLveSort() {// if (hoList != null && hoList.size() > 0) {// for (Hotspot hotspot : hoList) {// byLve = hotspot.getLve();// }//// Collections.sort(hoList, new Comparator() {//// @Override// public int compare(Object object1, Object object2) {// // TODO Auto-generated method stub// Hotspot h1 = (Hotspot)object1;// Hotspot h2 = (Hotspot)object2;// if(h1.getLve() != null && )// return 0;// }//// });// }// }//}
源码下载: