Android:简单的ListView下拉刷新,上拉加载

效果也差不多.
设置一个自定义的ListView(类名ReFlashListView)然后往里添加headler(头)布局和Footer累加到后面试图

package com.example.xialashuxin;

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.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

import static android.content.ContentValues.TAG;

public class ReFlashListView extends ListView implements OnScrollListener {
    View header;// 顶部布局文件;
    int headerHeight;// 顶部布局文件的高度;
    int firstVisibleItem;// 当前第一个可见的item的位置;
    int scrollState;// listview 当前滚动状态;
    boolean isRemark;// 标记,当前是在listview最顶端摁下的;
    int startY;// 摁下时的Y值;

    int state;// 当前的状态;
    final int NONE = 0;// 正常状态;
    final int PULL = 1;// 提示下拉状态;
    final int RELESE = 2;// 提示释放状态;
    final int REFLASHING = 3;// 刷新状态;
    IReflashListner iReflashListener;//刷新数据的接口

    public ReFlashListView(Context context) {
        super(context);
        initView(context);
    }

    public ReFlashListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ReFlashListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    /**
     * 初始化界面,添加顶部布局文件到 listview
     *
     * @param context
     */
    private void initView(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        header = inflater.inflate(R.layout.header_layout, null);//下拉刷新试图
        measureView(header);
        headerHeight = header.getMeasuredHeight();
        topPadding(-headerHeight);//设置内边高度为负数是就会隐藏
        this.addHeaderView(header);
        View inflate = View.inflate(context, R.layout.load_layout, null);//上拉加载
        this.addFooterView(inflate);
        this.setOnScrollListener(this);
    }

    /**
     * 通知父布局,占用的宽,高;
     *
     * @param view
     */
    private void measureView(View view) {
        ViewGroup.LayoutParams p = view.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
        int height;
        int tempHeight = p.height;
        if (tempHeight > 0) {
            height = MeasureSpec.makeMeasureSpec(tempHeight,
                    MeasureSpec.EXACTLY);
        } else {
            height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        view.measure(width, height);
    }

    /**
     * 设置header 布局 上边距;
     *
     * @param topPadding
     */
    private void topPadding(int topPadding) {
        header.setPadding(header.getPaddingLeft(), topPadding,
                header.getPaddingRight(), header.getPaddingBottom());
        header.invalidate();
    }

    int firstVisibleItemjiehe;
    int totalItemCount;
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
        this.firstVisibleItem = firstVisibleItem;
        firstVisibleItemjiehe=firstVisibleItem+visibleItemCount;
        this.totalItemCount=totalItemCount;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        this.scrollState = scrollState;
        if(firstVisibleItemjiehe==totalItemCount){
            iReflashListener.onEndflash();
            Log.e(TAG, "onScrollStateChanged: 我走了" );
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (firstVisibleItem == 0) {
                    isRemark = true;
                    startY = (int) ev.getY();//按下时的值5
                }

                break;
            case MotionEvent.ACTION_MOVE://移动时
                onMove(ev);
                break;
            case MotionEvent.ACTION_UP://抬起时
                if (state == RELESE) {
                    state = REFLASHING;
                    // 加载最新数据;
                    reflashViewByState();
                    iReflashListener.onReflash();
                } else if (state == PULL) {
                    state = NONE;
                    isRemark = false;
                    reflashViewByState();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 判断移动过程操作;
     *
     * @param ev
     */
    private void onMove(MotionEvent ev) {
        if (!isRemark) {
            return;
        }
        int tempY = (int) ev.getY();
        int space = tempY - startY;
        int topPadding = space - headerHeight;
        switch (state) {
            case NONE:
                if (space > 0) {
                    state = PULL;
                    reflashViewByState();
                }
                break;
            case PULL:
                topPadding(topPadding);
                if (space > headerHeight + 30
                        && scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    state = RELESE;
                    reflashViewByState();
                }
                break;
            case RELESE:
                topPadding(topPadding);//负数越来越少变成正数
                if (space < headerHeight + 30) {
                    state = PULL;
                    reflashViewByState();
                } else if (space <= 0) {
                    state = NONE;
                    isRemark = false;
                    reflashViewByState();
                }
                break;
        }
    }

    /**
     * 根据当前状态,改变界面显示;
     */
    private void reflashViewByState() {
        TextView tip = (TextView) header.findViewById(R.id.tip);
        ImageView arrow = (ImageView) header.findViewById(R.id.arrow);
        ProgressBar progress = (ProgressBar) header.findViewById(R.id.progress);
        RotateAnimation anim = new RotateAnimation(0, 180,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        anim.setDuration(500);
        anim.setFillAfter(true);
        RotateAnimation anim1 = new RotateAnimation(180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        anim1.setDuration(500);
        anim1.setFillAfter(true);
        switch (state) {
            case NONE:
                arrow.clearAnimation();
                topPadding(-headerHeight);
                break;

            case PULL:
                arrow.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                tip.setText("下拉可以刷新!");
                arrow.clearAnimation();
                arrow.setAnimation(anim1);
                break;
            case RELESE:
                arrow.setVisibility(View.VISIBLE);
                progress.setVisibility(View.GONE);
                tip.setText("松开可以刷新!");
                arrow.clearAnimation();
                arrow.setAnimation(anim);
                break;
            case REFLASHING:
                topPadding(50);
                arrow.setVisibility(View.GONE);
                progress.setVisibility(View.VISIBLE);
                tip.setText("正在刷新...");
                arrow.clearAnimation();
                break;
        }
    }

    /**
     * 获取完数据;
     */
    public void reflashComplete() {
        state = NONE;
        isRemark = false;
        reflashViewByState();
        TextView lastupdatetime = (TextView) header
                .findViewById(R.id.tip_time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        lastupdatetime.setText(time);
    }
//在主activity你调用
    public void setInterface(IReflashListner iReflashListener){
        this.iReflashListener = iReflashListener;
    }
    /**
     * 刷新数据接口
     * @author Administrator
     */
    public interface IReflashListner{
        void onReflash();
        void onEndflash();
    }

}

头布局header_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="10dip"
        >

        <LinearLayout
            android:id="@+id/layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/tip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="下了可以刷新"/>

            <TextView
                android:id="@+id/tip_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="下了可以刷新时间"/>
        </LinearLayout>

        <ImageView
            android:id="@+id/arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_toLeftOf="@id/layout"
            android:src="@drawable/qiyi_search_hotwor_rank_status_down"
            ></ImageView>

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginRight="10dp"
            android:layout_toLeftOf="@id/layout"
            ></ProgressBar>
    </RelativeLayout>
</LinearLayout>

load_layout加载的布局底部

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textColor="#f0f"
    android:text="拼命加载中...."/>
</LinearLayout>

使用ListView时要使用自定义的呀(activity_mian.xml)

<com.example.xialashuxin.ReFlashListView
        android:id="@+id/listview_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></com.example.xialashuxin.ReFlashListView>

主代码中要注意设置setInterface不然会报接口方法空哦,空指针...

package com.example.xialashuxin;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements ReFlashListView.IReflashListner {
    private ReFlashListView listviewText;
    private MyAdapter mMyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listviewText = (ReFlashListView) findViewById(R.id.listview_text);
         mMyAdapter = new MyAdapter();
        listviewText.setInterface(this);
        listviewText.setAdapter(mMyAdapter);

    }

    @Override
    public void onReflash() {
        Log.e("tag", "onReflash: 我刷新了哦" );
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                //获取最新数据
//                setReflashData();
                //通知界面显示
//                showList(apk_list);
                //通知listview 刷新数据完毕;
                listviewText.reflashComplete();
            }
        }, 2000);
    }
    int a=20;
    @Override
    public void onEndflash() {
        a=a+100;
        mMyAdapter.notifyDataSetChanged();
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return a;
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view=View.inflate(MainActivity.this,R.layout.item,null);
            TextView viewById = view.findViewById(R.id.textview);
            viewById.setText("我去");
            return view;
        }
    }
}

item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="40sp"
    android:id="@+id/textview"/>
</LinearLayout>

效果图

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,638评论 25 708
  • 前段时间自己写了一个能够“通用”的,支持下拉刷新和上拉加载的自定义控件。可能现如今这已经不新鲜了,但有兴趣的朋友还...
    Machivellia阅读 7,362评论 19 112
  • 阿弥陀佛!诸位善知识今天我们继续共同学习受持《六祖法宝坛经浅释》!感恩法缘殊胜!感恩法缘大慈!感恩因缘和合 !感恩...
    了悟菩提阅读 1,090评论 0 0
  • 不知道说起甘南你会想到什么?我实在是猜不到,因为我有属于自己对甘南的记忆与感情。 那时候因为毕业,我们...
    东清儿阅读 213评论 0 0
  • 楔子:昨天有刚化作人形的妖精问我岁数,我看了看远处的云山,笑了笑不说话,他怎么会相信我在招摇山已待了数千年,数千年...
    沈三班班阅读 261评论 0 0