成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

Android中ListView下拉刷新的實現(xiàn)代碼

Android中ListView下拉刷新

新蔡ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!

實現(xiàn)效果圖:

Android中ListView下拉刷新的實現(xiàn)代碼

ListView中的下拉刷新是非常常見的,也是經(jīng)常使用的,看到有很多同學(xué)想要,那我就整理一下,供大家參考。那我就不解釋,直接上代碼了。

這里需要自己重寫一下ListView,重寫代碼如下:

package net.loonggg.listview; 
 
import java.util.Date; 
 
import android.content.Context; 
import android.util.AttributeSet; 
import android.view.LayoutInflater; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.animation.LinearInterpolator; 
import android.view.animation.RotateAnimation; 
import android.widget.AbsListView; 
import android.widget.AbsListView.OnScrollListener; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.ListView; 
import android.widget.ProgressBar; 
import android.widget.TextView; 
 
public class MyListView extends ListView implements OnScrollListener { 
 
  private final static int RELEASE_To_REFRESH = 0;// 下拉過程的狀態(tài)值 
  private final static int PULL_To_REFRESH = 1; // 從下拉返回到不刷新的狀態(tài)值 
  private final static int REFRESHING = 2;// 正在刷新的狀態(tài)值 
  private final static int DONE = 3; 
  private final static int LOADING = 4; 
 
  // 實際的padding的距離與界面上偏移距離的比例 
  private final static int RATIO = 3; 
  private LayoutInflater inflater; 
 
  // ListView頭部下拉刷新的布局 
  private LinearLayout headerView; 
  private TextView lvHeaderTipsTv; 
  private TextView lvHeaderLastUpdatedTv; 
  private ImageView lvHeaderArrowIv; 
  private ProgressBar lvHeaderProgressBar; 
 
  // 定義頭部下拉刷新的布局的高度 
  private int headerContentHeight; 
 
  private RotateAnimation animation; 
  private RotateAnimation reverseAnimation; 
 
  private int startY; 
  private int state; 
  private boolean isBack; 
 
  // 用于保證startY的值在一個完整的touch事件中只被記錄一次 
  private boolean isRecored; 
 
  private OnRefreshListener refreshListener; 
 
  private boolean isRefreshable; 
 
  public MyListView(Context context) { 
    super(context); 
    init(context); 
  } 
 
  public MyListView(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); 
    headerView = (LinearLayout) inflater.inflate(R.layout.lv_header, null); 
    lvHeaderTipsTv = (TextView) headerView 
        .findViewById(R.id.lvHeaderTipsTv); 
    lvHeaderLastUpdatedTv = (TextView) headerView 
        .findViewById(R.id.lvHeaderLastUpdatedTv); 
 
    lvHeaderArrowIv = (ImageView) headerView 
        .findViewById(R.id.lvHeaderArrowIv); 
    // 設(shè)置下拉刷新圖標的最小高度和寬度 
    lvHeaderArrowIv.setMinimumWidth(70); 
    lvHeaderArrowIv.setMinimumHeight(50); 
 
    lvHeaderProgressBar = (ProgressBar) headerView 
        .findViewById(R.id.lvHeaderProgressBar); 
    measureView(headerView); 
    headerContentHeight = headerView.getMeasuredHeight(); 
    // 設(shè)置內(nèi)邊距,正好距離頂部為一個負的整個布局的高度,正好把頭部隱藏 
    headerView.setPadding(0, -1 * headerContentHeight, 0, 0); 
    // 重繪一下 
    headerView.invalidate(); 
    // 將下拉刷新的布局加入ListView的頂部 
    addHeaderView(headerView, null, false); 
    // 設(shè)置滾動監(jiān)聽事件 
    setOnScrollListener(this); 
 
    // 設(shè)置旋轉(zhuǎn)動畫事件 
    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); 
 
    // 一開始的狀態(tài)就是下拉刷新完的狀態(tài),所以為DONE 
    state = DONE; 
    // 是否正在刷新 
    isRefreshable = false; 
  } 
 
  @Override 
  public void onScrollStateChanged(AbsListView view, int scrollState) { 
 
  } 
 
  @Override 
  public void onScroll(AbsListView view, int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 
        if (firstVisibleItem == 0) { 
          isRefreshable = true; 
         } else { 
          isRefreshable = false; 
         }   
    } 
 
  @Override 
  public boolean onTouchEvent(MotionEvent ev) { 
    if (isRefreshable) { 
      switch (ev.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
        if (!isRecored) { 
          isRecored = true; 
          startY = (int) ev.getY();// 手指按下時記錄當前位置 
        } 
        break; 
      case MotionEvent.ACTION_UP: 
        if (state != REFRESHING && state != LOADING) { 
          if (state == PULL_To_REFRESH) { 
            state = DONE; 
            changeHeaderViewByState(); 
          } 
          if (state == RELEASE_To_REFRESH) { 
            state = REFRESHING; 
            changeHeaderViewByState(); 
            onLvRefresh(); 
          } 
        } 
        isRecored = false; 
        isBack = false; 
 
        break; 
 
      case MotionEvent.ACTION_MOVE: 
        int tempY = (int) ev.getY(); 
        if (!isRecored) { 
          isRecored = true; 
          startY = tempY; 
        } 
        if (state != REFRESHING && isRecored && state != LOADING) { 
          // 保證在設(shè)置padding的過程中,當前的位置一直是在head,否則如果當列表超出屏幕的話,當在上推的時候,列表會同時進行滾動 
          // 可以松手去刷新了 
          if (state == RELEASE_To_REFRESH) { 
            setSelection(0); 
            // 往上推了,推到了屏幕足夠掩蓋head的程度,但是還沒有推到全部掩蓋的地步 
            if (((tempY - startY) / RATIO < headerContentHeight)// 由松開刷新狀態(tài)轉(zhuǎn)變到下拉刷新狀態(tài) 
                && (tempY - startY) > 0) { 
              state = PULL_To_REFRESH; 
              changeHeaderViewByState(); 
            } 
            // 一下子推到頂了 
            else if (tempY - startY <= 0) {// 由松開刷新狀態(tài)轉(zhuǎn)變到done狀態(tài) 
              state = DONE; 
              changeHeaderViewByState(); 
            } 
          } 
          // 還沒有到達顯示松開刷新的時候,DONE或者是PULL_To_REFRESH狀態(tài) 
          if (state == PULL_To_REFRESH) { 
            setSelection(0); 
            // 下拉到可以進入RELEASE_TO_REFRESH的狀態(tài) 
            if ((tempY - startY) / RATIO >= headerContentHeight) {// 由done或者下拉刷新狀態(tài)轉(zhuǎn)變到松開刷新 
              state = RELEASE_To_REFRESH; 
              isBack = true; 
              changeHeaderViewByState(); 
            } 
            // 上推到頂了 
            else if (tempY - startY <= 0) {// 由DOne或者下拉刷新狀態(tài)轉(zhuǎn)變到done狀態(tài) 
              state = DONE; 
              changeHeaderViewByState(); 
            } 
          } 
          // done狀態(tài)下 
          if (state == DONE) { 
            if (tempY - startY > 0) { 
              state = PULL_To_REFRESH; 
              changeHeaderViewByState(); 
            } 
          } 
          // 更新headView的size 
          if (state == PULL_To_REFRESH) { 
            headerView.setPadding(0, -1 * headerContentHeight 
                + (tempY - startY) / RATIO, 0, 0); 
 
          } 
          // 更新headView的paddingTop 
          if (state == RELEASE_To_REFRESH) { 
            headerView.setPadding(0, (tempY - startY) / RATIO 
                - headerContentHeight, 0, 0); 
          } 
 
        } 
        break; 
 
      default: 
        break; 
      } 
    } 
    return super.onTouchEvent(ev); 
  } 
 
  // 當狀態(tài)改變時候,調(diào)用該方法,以更新界面 
  private void changeHeaderViewByState() { 
    switch (state) { 
    case RELEASE_To_REFRESH: 
      lvHeaderArrowIv.setVisibility(View.VISIBLE); 
      lvHeaderProgressBar.setVisibility(View.GONE); 
      lvHeaderTipsTv.setVisibility(View.VISIBLE); 
      lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
 
      lvHeaderArrowIv.clearAnimation();// 清除動畫 
      lvHeaderArrowIv.startAnimation(animation);// 開始動畫效果 
 
      lvHeaderTipsTv.setText("松開刷新"); 
      break; 
    case PULL_To_REFRESH: 
      lvHeaderProgressBar.setVisibility(View.GONE); 
      lvHeaderTipsTv.setVisibility(View.VISIBLE); 
      lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
      lvHeaderArrowIv.clearAnimation(); 
      lvHeaderArrowIv.setVisibility(View.VISIBLE); 
      // 是由RELEASE_To_REFRESH狀態(tài)轉(zhuǎn)變來的 
      if (isBack) { 
        isBack = false; 
        lvHeaderArrowIv.clearAnimation(); 
        lvHeaderArrowIv.startAnimation(reverseAnimation); 
 
        lvHeaderTipsTv.setText("下拉刷新"); 
      } else { 
        lvHeaderTipsTv.setText("下拉刷新"); 
      } 
      break; 
 
    case REFRESHING: 
 
      headerView.setPadding(0, 0, 0, 0); 
 
      lvHeaderProgressBar.setVisibility(View.VISIBLE); 
      lvHeaderArrowIv.clearAnimation(); 
      lvHeaderArrowIv.setVisibility(View.GONE); 
      lvHeaderTipsTv.setText("正在刷新..."); 
      lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
      break; 
    case DONE: 
      headerView.setPadding(0, -1 * headerContentHeight, 0, 0); 
 
      lvHeaderProgressBar.setVisibility(View.GONE); 
      lvHeaderArrowIv.clearAnimation(); 
      lvHeaderArrowIv.setImageResource(R.drawable.arrow); 
      lvHeaderTipsTv.setText("下拉刷新"); 
      lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
      break; 
    } 
  } 
 
  // 此方法直接照搬自網(wǎng)絡(luò)上的一個下拉刷新的demo,此處是“估計”headView的width以及height 
  private void measureView(View child) { 
    ViewGroup.LayoutParams params = child.getLayoutParams(); 
    if (params == null) { 
      params = new ViewGroup.LayoutParams( 
          ViewGroup.LayoutParams.FILL_PARENT, 
          ViewGroup.LayoutParams.WRAP_CONTENT); 
    } 
    int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, 
        params.width); 
    int lpHeight = params.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 setonRefreshListener(OnRefreshListener refreshListener) { 
    this.refreshListener = refreshListener; 
    isRefreshable = true; 
  } 
 
  public interface OnRefreshListener { 
    public void onRefresh(); 
  } 
 
  public void onRefreshComplete() { 
    state = DONE; 
    lvHeaderLastUpdatedTv.setText("最近更新:" + new Date().toLocaleString()); 
    changeHeaderViewByState(); 
  } 
 
  private void onLvRefresh() { 
    if (refreshListener != null) { 
      refreshListener.onRefresh(); 
    } 
  } 
 
  public void setAdapter(LvAdapter adapter) { 
    lvHeaderLastUpdatedTv.setText("最近更新:" + new Date().toLocaleString()); 
    super.setAdapter(adapter); 
  } 
 
} 

重寫完ListView之后,在布局文件中是這么使用的,頭部下拉刷新的布局文件lv_header.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?> 
<!-- ListView的頭部 --> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:background="#000000" > 
 
  <!-- 內(nèi)容 --> 
 
  <RelativeLayout 
    android:id="@+id/head_contentLayout" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingLeft="30dp" > 
 
    <!-- 箭頭圖像、進度條 --> 
 
    <FrameLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_centerVertical="true" > 
 
      <!-- 箭頭 --> 
 
      <ImageView 
        android:id="@+id/lvHeaderArrowIv" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center" 
        android:src="@drawable/arrow" /> 
 
      <!-- 進度條 --> 
 
      <ProgressBar 
        android:id="@+id/lvHeaderProgressBar" 
         
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center" 
        android:visibility="gone" /> 
    </FrameLayout> 
 
    <!-- 提示、最近更新 --> 
 
    <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_centerHorizontal="true" 
      android:gravity="center_horizontal" 
      android:orientation="vertical" > 
 
      <!-- 提示 --> 
 
      <TextView 
        android:id="@+id/lvHeaderTipsTv" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="下拉刷新" 
        android:textColor="@color/white" 
        android:textSize="20sp" /> 
 
      <!-- 最近更新 --> 
 
      <TextView 
        android:id="@+id/lvHeaderLastUpdatedTv" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="上次更新" 
        android:textColor="@color/gold" 
        android:textSize="10sp" /> 
    </LinearLayout> 
  </RelativeLayout> 
 
</LinearLayout> 

在Main.xml中進行設(shè)置,代碼如下:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:background="#000000" 
  android:orientation="vertical" > 
 
  <net.loonggg.listview.MyListView 
    android:id="@+id/lv" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 
 
</LinearLayout> 

然后就是在MainActivity中實現(xiàn),代碼如下:

package net.loonggg.listview; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import net.loonggg.listview.MyListView.OnRefreshListener; 
import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
 
public class MainActivity extends Activity { 
  private List<String> list; 
  private MyListView lv; 
  private LvAdapter adapter; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    lv = (MyListView) findViewById(R.id.lv); 
    list = new ArrayList<String>(); 
    list.add("loonggg"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    list.add("我們都是開發(fā)者"); 
    adapter = new LvAdapter(list, this); 
    lv.setAdapter(adapter); 
 
    lv.setonRefreshListener(new OnRefreshListener() { 
 
      @Override 
      public void onRefresh() { 
        new AsyncTask<Void, Void, Void>() { 
          protected Void doInBackground(Void... params) { 
            try { 
              Thread.sleep(1000); 
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
            list.add("刷新后添加的內(nèi)容"); 
            return null; 
          } 
 
          @Override 
          protected void onPostExecute(Void result) { 
            adapter.notifyDataSetChanged(); 
            lv.onRefreshComplete(); 
          } 
        }.execute(null, null, null); 
      } 
    }); 
  } 
} 

這里還需要為ListView設(shè)置一下Adapter,自定義的Adapter如下:

package net.loonggg.listview; 
 
import java.util.List; 
 
import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 
 
public class LvAdapter extends BaseAdapter { 
  private List<String> list; 
  private Context context; 
 
  public LvAdapter(List<String> list, Context context) { 
    this.list = list; 
    this.context = context; 
  } 
 
  @Override 
  public int getCount() { 
    return list.size(); 
  } 
 
  @Override 
  public Object getItem(int position) { 
    return list.get(position); 
  } 
 
  @Override 
  public long getItemId(int position) { 
    return position; 
  } 
 
  @Override 
  public View getView(int position, View convertView, ViewGroup parent) { 
    TextView tv = new TextView(context.getApplicationContext()); 
    tv.setText(list.get(position)); 
    return tv; 
  } 
 
} 

到這里就完了,代碼中的解釋非常詳細,具體的我就不多說了,也不解釋了,自己看看并研究吧!

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

網(wǎng)頁題目:Android中ListView下拉刷新的實現(xiàn)代碼
本文鏈接:http://jinyejixie.com/article48/gpeeep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站關(guān)鍵詞優(yōu)化、外貿(mào)網(wǎng)站建設(shè)網(wǎng)站制作、網(wǎng)站策劃、搜索引擎優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化
思南县| 兖州市| 儋州市| 柞水县| 岳阳市| 兖州市| 河南省| 东乌珠穆沁旗| 房山区| 琼结县| 会同县| 连云港市| 石家庄市| 民和| 济源市| 大城县| 怀集县| 台南县| 定远县| 海南省| 鄂温| 东城区| 金门县| 义马市| 循化| 通州区| 怀来县| 灯塔市| 肥乡县| 容城县| 湾仔区| 灵武市| 汶川县| 甘洛县| 山东省| 胶州市| 广平县| 个旧市| 明光市| 吉木萨尔县| 武定县|