標籤:end 項目 public odi too package undle 資訊 記錄
先上:
使用網路應用時,比如QQ、這些,我們經常會通過下拉實現訊息的重新整理。下面記錄一種通過調用第三方檔案實現下拉重新整理ListView的方法
步驟一、先在github中搜尋Android-PullToRefresh-master並下載
步驟二、在AndroidStudio中建立一個項目,右鍵Importt Module匯入Android-PullToRefresh-master中的library檔案(注意調整好項目的sdk和jdk版本)如何匯入類庫檔案?
步驟三、複製類庫檔案library中的PullToRefreshListView.java的路徑到自己建立的項目中的布局檔案中,並給它添加寬高和id,如下
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.contentprovide.liuliu.demo_3_3_7.MainActivity"> <com.handmark.pulltorefresh.library.PullToRefreshListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/my_listview" ></com.handmark.pulltorefresh.library.PullToRefreshListView></LinearLayout>
步驟四、在java檔案中使用集合和適配器給集合添加清單項目內容,在非同步線程中處理重新整理行為,並且在ListView對象中的監聽事件中執行非同步線程
package com.contentprovide.liuliu.demo_3_3_7;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshListView;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity { PullToRefreshListView my_listview; //定義一個集合對象用於存放listview的清單項目內容 List<String> list;// 定義一個ListView適配器 ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); my_listview = (PullToRefreshListView) findViewById(R.id.my_listview); list = new ArrayList<>(); list.add("Item1"); list.add("Item2"); list.add("Item3"); list.add("Item4"); arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,list);// 把適配器添加ListView對象中 my_listview.setAdapter(arrayAdapter);// 設定事件監聽器 my_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {// 執行非同步線程 asyncTask.execute(); } }); }// 在非同步線程中處理重新整理行為 AsyncTask<Void,Void,Void> asyncTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) {// 手動休眠三秒,模仿從伺服器端擷取資訊的延遲 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); list.add("新增加的Item1"); list.add("新增加的Item2");// 通知ListView對象重新整理完成 my_listview.onRefreshComplete(); } };}
安卓實現下拉重新整理效果