android 自定义ListView下拉刷新控件——自定义控件学习(五)

来源:互联网 发布:js强制弹窗代码 编辑:程序博客网 时间:2024/05/21 09:47

android 自定义ListView下拉刷新控件——自定义控件学习(五)

android的ListView使用的时候经常需要做一个下拉刷新的功能。这样的功能可能需要的很多,如果每次都重新做一遍的话,有点麻烦了,所以,这里把这个功能制作成一个控件,如果对这个控件的实现有兴趣,可以参考:android ListView下拉刷新。

好了,下面上货:

1、首先是重要的CustomerListViewPullDownRefreshAndPageLoad.java

package com.example.administrator.customerpulldownrefreshandpageload;import android.content.Context;import android.os.Handler;import android.os.Message;import android.util.AttributeSet;import android.util.Log;import android.view.Gravity;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.ProgressBar;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast;/** * Created by Administrator on 2016-09-27. */public class CustomerListViewPullDownRefreshAndPageLoad extends RelativeLayout{    private final String TAG = CustomerListViewPullDownRefreshAndPageLoad.class.getSimpleName();    private final int MSG_CODE = 0x994;    private ListView listView;    private ArrayAdapter<String> adapter;    private ViewGroup.MarginLayoutParams marginLayoutParams;    private ViewGroup.MarginLayoutParams marginLayoutParamspro;    //上方的存放图标和文字的LinearLayout    private LinearLayout linearLayout;    //在上方存档的内容包括以下的imageView progressBar textView    private ImageView imageArrow;    private ProgressBar progressBar;    private TextView textViewTip;    private final int MARGIN_TOP = -200;    private boolean pullFlag;    private boolean returnFlag;    //刷新完成标志    private boolean refreshFinishFlag;    private int oldY;    private int newY;    private int distance;    //线程    public Thread tempThead;    //接口    public interface refreshEvent{        void refresh();    }    private refreshEvent refreshEvent;    public CustomerListViewPullDownRefreshAndPageLoad(Context context, AttributeSet attrs) {        super(context, attrs);        listView = new ListView(getContext());        RelativeLayout.LayoutParams relayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);        relayoutParams.setMargins(0,0,0,0);        listView.setLayoutParams(relayoutParams);        listView.setBackgroundColor(getResources().getColor(android.R.color.white));        addView(listView);        linearLayout = new LinearLayout(getContext());        RelativeLayout.LayoutParams lilayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);        lilayoutParams.setMargins(0,MARGIN_TOP,0,0);        linearLayout.setOrientation(LinearLayout.HORIZONTAL);//        linearLayout.setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));        linearLayout.setGravity(Gravity.CENTER);        linearLayout.setLayoutParams(lilayoutParams);        addView(linearLayout);        imageArrow = new ImageView(getContext());        imageArrow.setImageResource(R.drawable.arrowdown);        LinearLayout.LayoutParams imglayoutParams = new LinearLayout.LayoutParams(100,100);        imageArrow.setLayoutParams(imglayoutParams);        linearLayout.addView(imageArrow);        progressBar = new ProgressBar(getContext());        LinearLayout.LayoutParams prolayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);        progressBar.setProgressDrawable(getResources().getDrawable(android.R.drawable.progress_indeterminate_horizontal));        progressBar.setLayoutParams(prolayoutParams);        linearLayout.addView(progressBar);        textViewTip = new TextView(getContext());        LinearLayout.LayoutParams texlayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);        texlayoutParams.setMargins(20,0,0,0);        textViewTip.setText("正在刷新...");        textViewTip.setTextSize(20);        textViewTip.setLayoutParams(texlayoutParams);        linearLayout.addView(textViewTip);        pullFlag = false;        returnFlag = false;        refreshFinishFlag = true;        oldY = 0;        newY = 0;        distance = 0;        marginLayoutParams = (ViewGroup.MarginLayoutParams) listView.getLayoutParams();        marginLayoutParamspro = (ViewGroup.MarginLayoutParams) linearLayout.getLayoutParams();        //设置滑动事件        listView.setOnTouchListener(new MyOnTouch());    }    //滑动事件    class MyOnTouch implements View.OnTouchListener {        @Override        public boolean onTouch(View v, MotionEvent event) {            switch (event.getAction()) {                case MotionEvent.ACTION_DOWN:                    View firstChild = listView.getChildAt(0);                    if (firstChild != null) {                        //当前第一个是第几项                        int firstChildPosition = listView.getFirstVisiblePosition();                        //第一项的坐标为0                        int firstChildTop = firstChild.getTop();                        if (firstChildPosition == 0 && firstChildTop == 0 && refreshFinishFlag) {                            pullFlag = true;                            Log.i(TAG, "---->ACTION_DOWNpullFlag" + String.valueOf(pullFlag));                        }                        Log.i(TAG, "---->ACTION_DOWN" + String.valueOf(firstChildPosition));                        Log.i(TAG, "---->ACTION_DOWN" + String.valueOf(firstChildTop));                    }                    returnFlag = false;                    Log.i(TAG, "---->ACTION_DOWN");                    oldY = (int) event.getRawY(); distance = 0;                    break;                case MotionEvent.ACTION_MOVE:                    newY = (int) event.getRawY();                    distance = newY - oldY;                    if (pullFlag && distance > 0) {                        returnFlag = true;                        marginLayoutParams.topMargin = distance / 2;                        listView.setLayoutParams(marginLayoutParams);                        if (distance < 300) {                            //正在下拉                            downStatus();                            marginLayoutParamspro.topMargin = (distance / 2) - 100;                            linearLayout.setLayoutParams(marginLayoutParamspro);                            //防止强迫症,拉完有放回来                            refreshFinishFlag = true;                        } else {                            //下拉大于150,能够执行刷新动作                            //更新标志位,为完成下拉                            refreshFinishFlag = false;                            //显示释放                            upStatus();                        }                    }                    break;                case MotionEvent.ACTION_UP:                    Log.i(TAG, "---->ACTION_UP");                    if (pullFlag) {                        if (distance < 300) {                            //下拉没有到位释放                            marginLayoutParams.topMargin = 0;                            //隐藏上边的部分                            marginLayoutParamspro.topMargin = MARGIN_TOP;                            linearLayout.setLayoutParams(marginLayoutParamspro);                        } else {                            marginLayoutParams.topMargin = 200;                            //显示正在刷新                            refreshingStatus();                            //下拉到位释放,启动刷新线程                        tempThead = new Thread(){                            @Override                            public void run() {                                super.run();                                try {                                    Thread.sleep(3000);                                } catch (InterruptedException e) {                                    e.printStackTrace();                                }                                handler.obtainMessage(MSG_CODE).sendToTarget();                            }                        };                        tempThead.start();                        }                        listView.setLayoutParams(marginLayoutParams);                    }                    pullFlag = false;                    returnFlag = false;                    break;            }            //true时listview不能进行滑动,false时能够进行滑动            return returnFlag;        }    }    public void downStatus(){        imageArrow.setVisibility(View.VISIBLE);        progressBar.setVisibility(View.GONE);        imageArrow.setImageResource(R.drawable.arrowdown);        textViewTip.setText("下拉刷新...");    }    public void upStatus(){        imageArrow.setVisibility(View.VISIBLE);        progressBar.setVisibility(View.GONE);        imageArrow.setImageResource(R.drawable.arrowup);        textViewTip.setText("释放刷新...");    }    public void refreshingStatus(){        imageArrow.setVisibility(View.GONE);        progressBar.setVisibility(View.VISIBLE);        textViewTip.setText("正在刷新...");    }    public void setAdapter(ArrayAdapter<String> adapter) {        this.adapter = adapter;        listView.setAdapter(adapter);    }    private Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg.what == MSG_CODE){                Toast.makeText(getContext(), "刷新完成", Toast.LENGTH_SHORT).show();                refreshFinishFlag = true;                //插入刷新事件                refreshEvent.refresh();                //隐藏上边的部分                marginLayoutParamspro.topMargin = MARGIN_TOP;                linearLayout.setLayoutParams(marginLayoutParamspro);                //隐藏刷新界面                marginLayoutParams.topMargin = 0;                listView.setLayoutParams(marginLayoutParams);            }        }    };    public void setRefreshEvent(CustomerListViewPullDownRefreshAndPageLoad.refreshEvent refreshEvent) {        this.refreshEvent = refreshEvent;    }}



2、需要的资源:


是两张图片,用来显示下拉和松开。


3、调用,首先是布局文件:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.administrator.customerpulldownrefreshandpageload.MainActivity">    <com.example.administrator.customerpulldownrefreshandpageload.CustomerListViewPullDownRefreshAndPageLoad        android:layout_width="match_parent"        android:background="@android:color/darker_gray"        android:id="@+id/customListView"        android:layout_height="match_parent"></com.example.administrator.customerpulldownrefreshandpageload.CustomerListViewPullDownRefreshAndPageLoad></RelativeLayout>

4、调用,MainActivity.java

package com.example.administrator.customerpulldownrefreshandpageload;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import java.util.ArrayList;import java.util.List;import java.util.Random;public class MainActivity extends AppCompatActivity implements CustomerListViewPullDownRefreshAndPageLoad.refreshEvent {    private CustomerListViewPullDownRefreshAndPageLoad customerListViewPullDownRefreshAndPageLoad;    private List<String> data;    private ArrayAdapter<String> adapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        customerListViewPullDownRefreshAndPageLoad = (CustomerListViewPullDownRefreshAndPageLoad) this.findViewById(R.id.customListView);        data = new ArrayList<String>();        for (int i = 0; i < 30; i++) {            data.add("测试数据" + i);        }        adapter = new ArrayAdapter<String>(this, R.layout.simple_list, R.id.simple_list_textview, data);        customerListViewPullDownRefreshAndPageLoad.setAdapter(adapter);        customerListViewPullDownRefreshAndPageLoad.setRefreshEvent(this);    }    @Override    public void refresh() {        data.clear();        Random random = new Random();        for (int i = 0; i < 30; i++) {            data.add("测试数据" + String.valueOf(random.nextInt(100) + 1));        }        adapter.notifyDataSetChanged();    }    @Override    protected void onDestroy() {        customerListViewPullDownRefreshAndPageLoad.tempThead.stop();        super.onDestroy();    }}

注意:1、在MainActivity.java中需要实现refreshEvent接口,在接口中的refresh方法中写你的刷新操作。

   2、一定要记得在onDestroy中关闭子线程。

5、你可能需要的资源:


simple_list.xml

<?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="match_parent"        android:layout_height="wrap_content"        android:textColor="@color/colorAccent"        android:textSize="50sp"        android:id="@+id/simple_list_textview"/></LinearLayout>

下面是运行结果:






最后附上代码:点我下载,不要你的积分哦!!!

0 0
原创粉丝点击