Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android輪播圖封裝,下拉刷新相結合

Android輪播圖封裝,下拉刷新相結合

編輯:關於Android編程

自定義輪播圖CarouselView 自定義下拉刷新PullRefreshListView

馬上就要正式做畢業設計了,一些零碎時間寫其中的一個模塊,現記錄下來,以備以後忘記時使用。歡迎大神不吝糾正。

效果圖:
這裡寫圖片描述

layout_carousel.xml




    
    

    

        

        
        
    

carousel_dot_selected.xml



    

carousel_dot_unselect.xml



    

carousel_dot_selector.xml (輪播圖指示點選擇器)




 

輪播圖數據bean

package com.xing.carousel;

/**
 * Created by Administrator on 2016/3/22.
 */
public class CarouselData {
    private int id;

    private String title;

    private int resId;

    public CarouselData(int id, String title, int resId) {
        this.id = id;
        this.title = title;
        this.resId = resId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getResId() {
        return resId;
    }

    public void setResId(int resId) {
        this.resId = resId;
    }

    @Override
    public String toString() {
        return "CarouselData{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", resId=" + resId +
                '}';
    }
}

自定義輪播圖CarsouselView.java

package com.xing.carousel;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/3/22.
 */
public class CarouselView extends LinearLayout {

    private Context context;

    private List carouselDataList;

    private ViewPager viewPager;

    private TextView tv_title;

    private LinearLayout dotLayout;

    private List dotList;   //指示點

    private static final int MSG_UPDATE = 1;


    private Handler handler;


    public CarouselView(Context context) {
        this(context, null);
    }

    public CarouselView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    private void init() {
        LayoutInflater.from(context).inflate(R.layout.layout_carousel, this, true);
        initView();
        initData();

    }

    private void initData() {
        dotList = new ArrayList<>();
    }


    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tv_title = (TextView) findViewById(R.id.tv_title);
        dotLayout = (LinearLayout) findViewById(R.id.dot_layout);
    }


    public void start(List carouselDataList) {
        this.carouselDataList = carouselDataList;
        if (this.carouselDataList == null || this.carouselDataList.size() < 1) {
            return;
        }
        View view = null;
        LayoutParams params = new LayoutParams(5, 5);
        //根據輪播圖要顯示的數量來創建指示點的個數
        for (int i = 0; i < this.carouselDataList.size(); i++) {
            view = new View(context);
            //設置dot的寬和高,相當於在xml中設置layout_height和layout_width
            if (i != 0) {  //設置左邊距
                params.leftMargin = 5;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.carousel_dot_selector);
            dotList.add(view);  //加入到list集合中
            dotLayout.addView(view);  //加入父布局
        }

        viewPager.setAdapter(new MyPagerAdapter());

        viewPager.setOnPageChangeListener(new MyPagerChangeListener());

        updateTitleDot();

        if (handler == null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MSG_UPDATE:
                            int currentItem = viewPager.getCurrentItem();
                            if (currentItem < CarouselView.this.carouselDataList.size() - 1) {  //從0開始
                                currentItem++;
                            } else {
                                currentItem = 0;
                            }
                            viewPager.setCurrentItem(currentItem);
                            handler.sendEmptyMessageDelayed(MSG_UPDATE, 2000);
                            break;
                    }

                }
            };
            handler.sendEmptyMessageDelayed(MSG_UPDATE, 2000);
        }



    }


    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return carouselDataList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;

        }


        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final CarouselData carouselData = carouselDataList.get(position);
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(carouselData.getResId());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            container.addView(imageView);

            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    clickCallback.onClick(carouselData.getId(), position);
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            updateTitleDot();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private void updateTitleDot() {
        int currentPosition = viewPager.getCurrentItem() % carouselDataList.size();
        CarouselData carouselData = carouselDataList.get(currentPosition);
        tv_title.setText(carouselData.getTitle());
        for (int i = 0; i < carouselDataList.size(); i++) {
            dotLayout.getChildAt(i).setEnabled(i == currentPosition);
        }
    }


    ClickCallback clickCallback;

    interface ClickCallback {
        void onClick(int id, int position);
    }

    public void setClickCallback(ClickCallback clickCallback) {
        this.clickCallback = clickCallback;
    }
}

圓形進度條
progressbar_rotate.xml




    

        

        
    

下拉刷新控件

1.ListView頭布局
layout_pull_listview_header.xml




    


    <framelayout android:id="@+id/fl_progressbar_arrow" android:layout_height="wrap_content" android:layout_marginbottom="8dp" android:layout_margintop="8dp" android:layout_width="wrap_content">

        

        
    </framelayout>

    

        


        

    

ListView底部布局
layout_pull_listview_footer.xml




    


    


PullRefreshListView.java

package com.xing.carousel;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.Date;

/**
 * Created by Administrator on 2016/3/19.
 */
public class PullRefreshListView extends ListView implements AbsListView.OnScrollListener {

    private Context context;

    private View headerView;

    private final int STATE_PULL_REFRESH = 0;

    private final int STATE_RELEASE_REFRESH = 1;

    private final int STATE_REFRESHING = 2;

    private int currentState = STATE_PULL_REFRESH;

    private TextView mRefreshStatusTip;

    private TextView mRefreshTime;

    private ProgressBar mProgressBar;

    private ImageView mArrowImg;

    private int headerViewHeight;

    private int startY = -1;   //初始值

    private RotateAnimation upAnimation;

    private RotateAnimation downAnimation;

    private View footerView;

    private int footerViewHeight;

    public PullRefreshListView(Context context) {
        this(context, null);
    }

    public PullRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        context = getContext();
        initView();
        initData();


    }

    private void initData() {
        //初始化頭布局
        headerView.measure(0, 0);
        //得到頭布局高度
        headerViewHeight = headerView.getMeasuredHeight();
        //設置上邊距,隱藏頭布局
        headerView.setPadding(0, -headerViewHeight, 0, 0);
        //將頭布局添加至listView中
        this.addHeaderView(headerView, null, false); //頭布局selectable=false

        //初始化底部布局數據
        footerView.measure(0, 0);
        footerViewHeight = footerView.getMeasuredHeight();
        footerView.setPadding(0, 0, 0, -footerViewHeight);
        this.addFooterView(footerView, null, false);

        //初始化動畫
        initAnimation();

    }


    private void initView() {
        //初始化listView頭布局
        headerView = View.inflate(context, R.layout.layout_pull_listview_header, null);
        mProgressBar = (ProgressBar) headerView.findViewById(R.id.pb_refresh);
        mArrowImg = (ImageView) headerView.findViewById(R.id.iv_arrow);
        mRefreshStatusTip = (TextView) headerView.findViewById(R.id.tv_listview_top_tip);
        mRefreshTime = (TextView) headerView.findViewById(R.id.tv_listview_top_time);

        //初始化底部布局
        footerView = View.inflate(context, R.layout.layout_pull_listview_footer, null);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:

                //如果當前正在刷新,則不處理
                if (currentState == STATE_REFRESHING) {
                    break;
                }

                if (startY == -1) {
                    startY = (int) event.getRawY();   //保證startY有值
                }
                int deltaY = (int) (event.getRawY() - startY);  //手指移動的偏移量
                if (deltaY > 0 && getFirstVisiblePosition() == 0) {  //只有手指向下滑動(deltaY>0)並且第一個item為可見的時候,才下拉刷新
                    int paddingTop = -headerViewHeight + deltaY;
                    headerView.setPadding(0, paddingTop, 0, 0);  //將更新的padding設置給headerview,實時更新下拉布局的位置
                    if (paddingTop > 0 && currentState != STATE_RELEASE_REFRESH) {
                        currentState = STATE_RELEASE_REFRESH;
                        mArrowImg.startAnimation(upAnimation);
                    } else if (paddingTop < 0 && currentState != STATE_PULL_REFRESH) {
                        currentState = STATE_PULL_REFRESH;
                        mArrowImg.startAnimation(downAnimation);
                    }
                    return true;  //攔截move事件,不讓listview處理
                }
                break;

            case MotionEvent.ACTION_UP:

                startY = -1;  //重置

                if (currentState == STATE_PULL_REFRESH) {  //手指抬起時,如果當前狀態是下拉刷新,則直接隱藏頭布局。
                    headerView.setPadding(0, -headerViewHeight, 0, 0);

                } else if (currentState == STATE_RELEASE_REFRESH) {   //手指抬起時,如果當前狀態是松開刷新,則進入正在刷新狀態
                    currentState = STATE_REFRESHING;
                    //顯示正在刷新狀態
                    headerView.setPadding(0, 0, 0, 0);
                    //更新當前狀態
                    refreshHeaderState(currentState);

                    //監聽回調
                    if (onRefreshListener != null) {
                        onRefreshListener.onRefresh();
                    }
                }
                break;
        }
        return super.onTouchEvent(event);
    }


    private void refreshHeaderState(int currentState) {
        switch (currentState) {
            case STATE_PULL_REFRESH:
                mRefreshStatusTip.setText(getResources().getString(R.string.state_pull_refresh));
                mArrowImg.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.INVISIBLE);
                break;
            case STATE_RELEASE_REFRESH:
                mRefreshStatusTip.setText(getResources().getString(R.string.state_release_refresh));
                mArrowImg.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.INVISIBLE);
                break;
            case STATE_REFRESHING:
                mRefreshStatusTip.setText(getResources().getString(R.string.state_refreshing));
                mArrowImg.clearAnimation();  //清除動畫才能設置其可見性
                mArrowImg.setVisibility(View.INVISIBLE);
                mProgressBar.setVisibility(View.VISIBLE);
                mRefreshTime.setText(getResources().getString(R.string.last_refresh_time));
                break;
        }
    }


    private void initAnimation() {
        //向上旋轉動畫
        upAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        upAnimation.setDuration(300);
        upAnimation.setFillAfter(true);
        //向下旋轉動畫
        downAnimation = new RotateAnimation(-180, -360, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        downAnimation.setDuration(300);
        downAnimation.setFillAfter(true);
    }


    /**
     * 重置headerview中的刷新狀態和progressbar的顯示
     */
    public void resetHeaderFooterView() {
        currentState = STATE_PULL_REFRESH;
        mRefreshStatusTip.setText(getResources().getString(R.string.state_pull_refresh));
        mArrowImg.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    interface OnRefreshListener {
        void onRefresh();

        void loadMore();  //加載更多,通過listview的滾動監聽實現
    }

    OnRefreshListener onRefreshListener;

    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
    }


    /**
     * ListView的滑動監聽
     *
     * @param view
     * @param scrollState
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == OnScrollListener.SCROLL_STATE_FLING || scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (getLastVisiblePosition() == getCount() - 1) {   //滑動到最後一條,顯示tooterView
                footerView.setPadding(0, 0, 0, 0);
                setSelection(getCount() - 1);  //將最後一條拉到屏幕中顯示,這樣,footerview就可以顯示出來了,否則,footerview需要再次滑動才能顯示在屏幕中
            }
        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }


}

新建Android Project 測試demo




    


輪播圖作為頭布局添加到PullRefreshListView中
layout_header.xml




    

MainActivity.java

package com.xing.carousel;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private CarouselView carouselView;

    private List carouselDataList;

    private PullRefreshListView listView;


    private int[] resIds = {R.mipmap.ic_launcher, R.mipmap.top2, R.mipmap.back2};

    private List data;

    private View headerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (PullRefreshListView) findViewById(R.id.listView);
        headerView = View.inflate(this, R.layout.layout_header, null);
        carouselView = (CarouselView) headerView.findViewById(R.id.carsouelView);
        carouselDataList = new ArrayList<>();
        for (int i = 0; i < resIds.length; i++) {
            carouselDataList.add(new CarouselData(i, "標題" + i, resIds[i]));
        }

        carouselView.start(carouselDataList);
        data = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            data.add("ListView---->" + i);
        }

        listView.addHeaderView(headerView);
        listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data));

        carouselView.setClickCallback(new CarouselView.ClickCallback() {
            @Override
            public void onClick(int id, int position) {
                Toast.makeText(MainActivity.this, "你點擊了第" + position + "項", Toast.LENGTH_SHORT).show();
            }
        });


    }


}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved