上拉刷新
本文的上拉刷新需要用到 paginglistview 这个框架
public class MainActivity extends AppCompatActivity{ private PagingListView listView;//listview private MyPagingAdaper adapter;//适配器 //设置的三个集合 private List<String> firstList; private List<String> secondList; private List<String> thirdList; private int pager = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (PagingListView) findViewById(R.id.paging_list_view); adapter = new MyPagingAdaper(); initData(); listView.setAdapter(adapter); listView.setHasMoreItems(true);//用来判断是否还有更多的选项,确定footView的View是否显示还是progressBar显示出来 listView.setPagingableListener(new PagingListView.Pagingable() { @Override public void onLoadMoreItems() { if (pager < 3) { new CountryAsyncTask().execute(); } else { listView.onFinishLoading(false, null); } } }); } private void clearData() { pager = 0; adapter.removeAllItems(); listView.setHasMoreItems(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: clearData(); return true; default: return super.onOptionsItemSelected(item); } } private void initData() { firstList = new ArrayList<String>(); for (int i=0;i<12;i++){ firstList.add("这是一组第"+i+"个item"); } secondList = new ArrayList<String>(); for (int i=0;i<5;i++){ secondList.add("这是二组第"+i+"个item"); } thirdList = new ArrayList<String>(); for (int i=0;i<5;i++){ thirdList.add("这是三组第"+i+"个item"); } } private class CountryAsyncTask extends SafeAsyncTask<List<String>> { @Override public List<String> call() throws Exception { List<String> result = null; switch (pager) { case 0: result = firstList; break; case 1: result = secondList; break; case 2: result = thirdList; break; } Thread.sleep(3000); return result; } @Override protected void onSuccess(List<String> newItems) throws Exception { super.onSuccess(newItems); pager++; listView.onFinishLoading(true, newItems); } } }==================================
package test.huawei.com.mypulltorefresh; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; /** * Created by Administrator on 2016/10/30. */ public class LoadMoreView extends LinearLayout { public LoadMoreView(Context context) { super(context,null); } public LoadMoreView(Context context, AttributeSet attrs) { super(context, attrs,0); } public LoadMoreView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.lv_load_more,this); } }===================================
package test.huawei.com.mypulltorefresh; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.paging.listview.PagingBaseAdapter; public class MyPagingAdaper extends PagingBaseAdapter<String> { @Override public int getCount() { return items.size(); } @Override public String getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder ; if (convertView==null){ viewHolder = new ViewHolder(); convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.listviewitem, null); viewHolder.textView = (TextView)convertView.findViewById(R.id.textview); viewHolder.image = (ImageView) convertView.findViewById(R.id.image); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } String text = getItem(position); viewHolder.image.setImageResource(R.drawable.ic_action_refresh); viewHolder.textView.setText(text); // // // if (convertView != null) { // textView = (TextView) convertView; // } else { // textView = (TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_list_item_1, null); // } // textView.setText(text); return convertView; } public class ViewHolder{ ImageView image ; TextView textView; } }=============================
package test.huawei.com.mypulltorefresh; import android.os.Handler; import android.os.Looper; import android.util.Log; import java.io.InterruptedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * A class similar but unrelated to android's {@link android.os.AsyncTask}. * <p/> * Unlike AsyncTask, this class properly propagates exceptions. * <p/> * If you're familiar with AsyncTask and are looking for {@link android.os.AsyncTask#doInBackground(Object[])}, * we've named it {@link #call()} here to conform with java 1.5's {@link Callable} interface. * <p/> * Current limitations: does not yet handle progress, although it shouldn't be * hard to add. * <p/> * If using your own executor, you must call future() to get a runnable you can execute. * * @param <ResultT> */ public abstract class SafeAsyncTask<ResultT> implements Callable<ResultT> { public static final int DEFAULT_POOL_SIZE = 25; protected static final Executor DEFAULT_EXECUTOR = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); protected Handler handler; protected Executor executor; protected StackTraceElement[] launchLocation; protected FutureTask<Void> future; /** * Sets executor to Executors.newFixedThreadPool(DEFAULT_POOL_SIZE) and * Handler to new Handler() */ public SafeAsyncTask() { this.executor = DEFAULT_EXECUTOR; } /** * Sets executor to Executors.newFixedThreadPool(DEFAULT_POOL_SIZE) */ public SafeAsyncTask(Handler handler) { this.handler = handler; this.executor = DEFAULT_EXECUTOR; } /** * Sets Handler to new Handler() */ public SafeAsyncTask(Executor executor) { this.executor = executor; } public SafeAsyncTask(Handler handler, Executor executor) { this.handler = handler; this.executor = executor; } public FutureTask<Void> future() { future = new FutureTask<Void>(newTask()); return future; } public SafeAsyncTask<ResultT> executor(Executor executor) { this.executor = executor; return this; } public Executor executor() { return executor; } public SafeAsyncTask<ResultT> handler(Handler handler) { this.handler = handler; return this; } public Handler handler() { return handler; } public void execute() { execute(Thread.currentThread().getStackTrace()); } protected void execute(StackTraceElement[] launchLocation) { this.launchLocation = launchLocation; executor.execute(future()); } public boolean cancel(boolean mayInterruptIfRunning) { if (future == null) throw new UnsupportedOperationException("You cannot cancel this task before calling future()"); return future.cancel(mayInterruptIfRunning); } /** * @throws Exception, captured on passed to onException() if present. */ protected void onPreExecute() throws Exception { } /** * @param t the result of {@link #call()} * @throws Exception, captured on passed to onException() if present. */ @SuppressWarnings({"UnusedDeclaration"}) protected void onSuccess(ResultT t) throws Exception { } /** * Called when the thread has been interrupted, likely because * the task was canceled. * <p/> * By default, calls {@link #onException(Exception)}, but this method * may be overridden to handle interruptions differently than other * exceptions. * * @param e an InterruptedException or InterruptedIOException */ protected void onInterrupted(Exception e) { onException(e); } /** * Logs the exception as an Error by default, but this method may * be overridden by subclasses. * * @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)} * @throws RuntimeException, ignored */ protected void onException(Exception e) throws RuntimeException { onThrowable(e); } protected void onThrowable(Throwable t) throws RuntimeException { Log.e("roboguice", "Throwable caught during background processing", t); } /** * @throws RuntimeException, ignored */ protected void onFinally() throws RuntimeException { } protected Task<ResultT> newTask() { return new Task<ResultT>(this); } public static class Task<ResultT> implements Callable<Void> { protected SafeAsyncTask<ResultT> parent; protected Handler handler; public Task(SafeAsyncTask<ResultT> parent) { this.parent = parent; this.handler = parent.handler != null ? parent.handler : new Handler(Looper.getMainLooper()); } public Void call() throws Exception { try { doPreExecute(); doSuccess(doCall()); } catch (final Exception e) { try { doException(e); } catch (Exception f) { // logged but ignored Log.e("BACKGROUND_TASK", "Exception in", f); } } catch (final Throwable t) { try { doThrowable(t); } catch (Exception f) { // logged but ignored Log.e("BACKGROUND_TASK", "Exception in", f); } } finally { doFinally(); } return null; } protected void doPreExecute() throws Exception { postToUiThreadAndWait(new Callable<Object>() { public Object call() throws Exception { parent.onPreExecute(); return null; } }); } protected ResultT doCall() throws Exception { return parent.call(); } protected void doSuccess(final ResultT r) throws Exception { postToUiThreadAndWait(new Callable<Object>() { public Object call() throws Exception { parent.onSuccess(r); return null; } }); } protected void doException(final Exception e) throws Exception { if (parent.launchLocation != null) { final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace())); stack.addAll(Arrays.asList(parent.launchLocation)); e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()])); } postToUiThreadAndWait(new Callable<Object>() { public Object call() throws Exception { if (e instanceof InterruptedException || e instanceof InterruptedIOException) parent.onInterrupted(e); else parent.onException(e); return null; } }); } protected void doThrowable(final Throwable e) throws Exception { if (parent.launchLocation != null) { final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace())); stack.addAll(Arrays.asList(parent.launchLocation)); e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()])); } postToUiThreadAndWait(new Callable<Object>() { public Object call() throws Exception { parent.onThrowable(e); return null; } }); } protected void doFinally() throws Exception { postToUiThreadAndWait(new Callable<Object>() { public Object call() throws Exception { parent.onFinally(); return null; } }); } /** * Posts the specified runnable to the UI thread using a handler, * and waits for operation to finish. If there's an exception, * it captures it and rethrows it. * * @param c the callable to post * @throws Exception on error */ protected void postToUiThreadAndWait(final Callable c) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final Exception[] exceptions = new Exception[1]; // Execute onSuccess in the UI thread, but wait // for it to complete. // If it throws an exception, capture that exception // and rethrow it later. handler.post(new Runnable() { public void run() { try { c.call(); } catch (Exception e) { exceptions[0] = e; } finally { latch.countDown(); } } }); // Wait for onSuccess to finish latch.await(); if (exceptions[0] != null) throw exceptions[0]; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)