Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義控件實戰:帶下拉刷新與上拉加載的 DropDownListView

編輯:關於 Android 程式設計

本文記錄一個自定義 ListView 的實現過程,它在原生 ListView 基礎上擴展了下拉刷新與滾動到底部加載更多的能力,同時保留 ListView 本身的性能特性。

一、效果預覽

二、如何使用

2.1 在布局文件中聲明

<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:listviewattr="https://schemas.android.com/apk/res-auto">

    <com.nsu.app.dropdownlistviewdemo.dropdownlistview
        android:drawSelectorOnTop="false"
        android:id="@+id/list_view"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        listviewattr:isDropDownStyle="true"
        listviewattr:isOnBottomStyle="true"
        listviewattr:isAutoLoadOnBottom="true" />

</RelativeLayout>

控件自定義了三個 boolean 屬性:

<declare-styleable name="drop_down_list_attr">
    <attr name="isDropDownStyle" format="boolean" />
    <attr name="isOnBottomStyle" format="boolean" />
    <attr name="isAutoLoadOnBottom" format="boolean" />
</declare-styleable>
  • isDropDownStyle:是否啟用下拉樣式。Java 代碼中可設置下拉監聽器。
  • isOnBottomStyle:是否啟用底部樣式。Java 代碼中可設置滾動到底部的監聽器。
  • isAutoLoadOnBottom:滾動到底部時是否自動觸發監聽器,僅在 isOnBottomStyle 為 true 時有效。

值得注意的是:如果 isDropDownStyle 或 isOnBottomStyle 為 false,對應的 Header / Footer 布局根本不會加載,此時性能與原生 ListView 完全一致。

2.2 在 Java 代碼中使用

public class DropDownListViewDemo extends Activity {

    private LinkedList<String> listItems;
    private DropDownListView listView;
    private ArrayAdapter<String> adapter;

    private String[] mStrings = {"11111", "2222", "3333", "4444", "5555",
            "6666", "77777", "8888", "99999", "aaaaa", "bbbb", "cccc", "dddd", "eeee",};

    public static final int MORE_DATA_MAX_COUNT = 3;
    public int moreDataCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drop_down_list_view_demo);

        listView = (DropDownListView) findViewById(R.id.list_view);

        // 下拉刷新
        listView.setOnDropDownListener(new DropDownListView.OnDropDownListener() {
            @Override
            public void onDropDown() {
                new GetDataTask(true).execute();
            }
        });

        // 滾動到底部
        listView.setOnBottomListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new GetDataTask(false).execute();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Toast.makeText(DropDownListViewDemo.this,
                        R.string.drop_down_tip, Toast.LENGTH_LONG).show();
            }
        });

        listItems = new LinkedList<>();
        listItems.addAll(Arrays.asList(mStrings));
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
        listView.setAdapter(adapter);
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {
        private boolean isDropDown;

        public GetDataTask(boolean isDropDown) {
            this.isDropDown = isDropDown;
        }

        @Override
        protected String[] doInBackground(Void... params) {
            try {
                Thread.sleep(1000);   // 模擬網絡請求
            } catch (InterruptedException e) { }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            if (isDropDown) {
                listItems.addFirst("Added after drop down");
                adapter.notifyDataSetChanged();
                // 刷新結束後必須手動恢復狀態,注意要在 notifyDataSetChanged() 之後調用
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
                listView.onDropDownComplete(
                        getString(R.string.update_at) + dateFormat.format(new Date()));
            } else {
                moreDataCount++;
                listItems.add("Added after on bottom");
                adapter.notifyDataSetChanged();
                if (moreDataCount >= MORE_DATA_MAX_COUNT) {
                    listView.setHasMore(false);
                }
                listView.onBottomComplete();
            }
            super.onPostExecute(result);
        }
    }
}

使用要點:

  • setOnDropDownListener() 設置下拉事件,事件結束後需手動調用 onDropDownComplete() 恢復狀態(務必放在 adapter.notifyDataSetChanged() 之後)。
  • setOnBottomListener() 設置滾動到底部事件,結束後需調用 onBottomComplete()。

三、相關資源的定義

實現思路是在 ListView 上方加 Header、下方加 Footer。

3.1 下拉箭頭圖片

在 drawable 下放置名為 drop_down_list_arrow.png 的圖片即可。

3.2 文字資源(strings.xml)

<string name="drop_down_list_header_default_text">Click to refresh...</string>
<string name="drop_down_list_header_pull_text">Drop Down to refresh...</string>
<string name="drop_down_list_header_release_text">Release to refresh...</string>
<string name="drop_down_list_header_loading_text">Loading...</string>
<string name="drop_down_list_footer_default_text">More</string>
<string name="drop_down_list_footer_loading_text">Loading...</string>
<string name="drop_down_list_footer_no_more_text">No More</string>
<string name="drop_down_tip">Pull down to refresh or scroll to bottom to load more</string>
<string name="update_at">updated at:</string>

3.3 顏色資源(colors.xml)

<color name="drop_down_list_header_font_color">#000000</color>
<color name="drop_down_list_header_second_font_color">#000000</color>
<color name="drop_down_list_footer_font_color">#000000</color>

3.4 樣式資源(styles.xml,會覆蓋前面的 string / color 定義)

<style name="drop_down_list_header_progress_bar_style">
    <item name="android:minHeight">@dimen/drop_down_list_header_progress_bar_height</item>
    <item name="android:maxHeight">@dimen/drop_down_list_header_progress_bar_height</item>
</style>
<style name="drop_down_list_footer_progress_bar_style">
    <item name="android:minHeight">@dimen/drop_down_list_footer_progress_bar_height</item>
    <item name="android:maxHeight">@dimen/drop_down_list_footer_progress_bar_height</item>
</style>
<style name="drop_down_list_header_font_style">
    <item name="android:textColor">@color/drop_down_list_header_font_color</item>
    <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
</style>
<style name="drop_down_list_header_second_font_style">
    <item name="android:textColor">@color/drop_down_list_header_second_font_color</item>
    <item name="android:textAppearance">?android:attr/textAppearanceSmall</item>
</style>
<style name="drop_down_list_footer_font_style">
    <item name="android:textColor">@color/drop_down_list_footer_font_color</item>
    <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
</style>

3.5 尺寸資源(dimens.xml)

<dimen name="drop_down_list_header_padding_top">12dp</dimen>
<dimen name="drop_down_list_header_padding_bottom">15dp</dimen>
<dimen name="drop_down_list_header_progress_bar_height">36dp</dimen>
<dimen name="drop_down_list_footer_progress_bar_height">36dp</dimen>

四、核心代碼解析

控件繼承 ListView 並實現 OnScrollListener,通過 Header 的 paddingTop 變化模擬下拉手勢。

4.1 構造與初始化

public class DropDownListView extends ListView implements OnScrollListener {

    private boolean isDropDownStyle = true;
    private boolean isOnBottomStyle = true;
    private boolean isAutoLoadOnBottom = false;

    private Context context;
    private RelativeLayout headerLayout;
    private ImageView headerImage;
    private ProgressBar headerProgressBar;
    private TextView headerText;
    private TextView headerSecondText;

    private RelativeLayout footerLayout;
    private ProgressBar footerProgressBar;
    private Button footerButton;

    private OnDropDownListener onDropDownListener;
    private OnScrollListener onScrollListener;

    /** 下拉距離與 header paddingTop 的比例係數 */
    private float headerPaddingTopRate = 1.5f;
    /** header 可釋放觸發加載的最小距離 */
    private int headerReleaseMinDistance;

    private boolean hasMore = true;
    private boolean isShowFooterProgressBar = true;
    private boolean isShowFooterWhenNoMore = false;

    private int currentScrollState;
    private int currentHeaderStatus;
    private boolean hasReachedTop = false;

    private RotateAnimation flipAnimation;
    private RotateAnimation reverseFlipAnimation;

    private int headerOriginalHeight;
    private int headerOriginalTopPadding;
    private float actionDownPointY;
    private boolean isOnBottomLoading = false;

    public DropDownListView(Context context) {
        super(context);
        init(context);
    }

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

    public DropDownListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        getAttrs(context, attrs);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        initDropDownStyle();
        initOnBottomStyle();
        // 必須調用父類設置,才能回調 onScroll
        super.setOnScrollListener(this);
    }

4.2 初始化 Header

private void initDropDownStyle() {
    if (headerLayout != null) {
        if (isDropDownStyle) {
            addHeaderView(headerLayout);
        } else {
            removeHeaderView(headerLayout);
        }
        return;
    }
    if (!isDropDownStyle) return;

    headerReleaseMinDistance = context.getResources()
            .getDimensionPixelSize(R.dimen.drop_down_list_header_release_min_distance);

    flipAnimation = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    flipAnimation.setInterpolator(new LinearInterpolator());
    flipAnimation.setDuration(250);
    flipAnimation.setFillAfter(true);

    reverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    reverseFlipAnimation.setInterpolator(new LinearInterpolator());
    reverseFlipAnimation.setDuration(250);
    reverseFlipAnimation.setFillAfter(true);

    headerDefaultText = context.getString(R.string.drop_down_list_header_default_text);
    headerPullText = context.getString(R.string.drop_down_list_header_pull_text);
    headerReleaseText = context.getString(R.string.drop_down_list_header_release_text);
    headerLoadingText = context.getString(R.string.drop_down_list_header_loading_text);

    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    headerLayout = (RelativeLayout) inflater.inflate(R.layout.drop_down_list_header, this, false);
    headerText = (TextView) headerLayout.findViewById(R.id.drop_down_list_header_default_text);
    headerImage = (ImageView) headerLayout.findViewById(R.id.drop_down_list_header_image);
    headerProgressBar = (ProgressBar)
            headerLayout.findViewById(R.id.drop_down_list_header_progress_bar);
    headerSecondText = (TextView)
            headerLayout.findViewById(R.id.drop_down_list_header_second_text);

    headerLayout.setClickable(true);
    headerLayout.setOnClickListener(new OnClickListener() {
        @Override public void onClick(View v) { onDropDown(); }
    });

    headerText.setText(headerDefaultText);
    addHeaderView(headerLayout);

    measureHeaderLayout(headerLayout);
    headerOriginalHeight = headerLayout.getMeasuredHeight();
    headerOriginalTopPadding = headerLayout.getPaddingTop();
    currentHeaderStatus = HEADER_STATUS_CLICK_TO_LOAD;
}

4.3 觸摸事件:拖動 Header

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isDropDownStyle) {
        return super.onTouchEvent(event);
    }
    hasReachedTop = false;
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            actionDownPointY = event.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            adjustHeaderPadding(event);
            break;
        case MotionEvent.ACTION_UP:
            if (!isVerticalScrollBarEnabled()) {
                setVerticalScrollBarEnabled(true);
            }
            /**
             * 手指離開屏幕時:
             * - 若 header 狀態為 RELEASE_TO_LOAD,觸發 onDropDown
             * - 若為 DROP_DOWN_TO_LOAD,退回 CLICK_TO_LOAD 並隱藏 header
             */
            if (getFirstVisiblePosition() == 0 && currentHeaderStatus != HEADER_STATUS_LOADING) {
                switch (currentHeaderStatus) {
                    case HEADER_STATUS_RELEASE_TO_LOAD:
                        onDropDown();
                        break;
                    case HEADER_STATUS_DROP_DOWN_TO_LOAD:
                        setHeaderStatusClickToLoad();
                        setSecondPositionVisible();
                        break;
                    default:
                        break;
                }
            }
            break;
    }
    return super.onTouchEvent(event);
}

4.4 滾動監聽:狀態切換與自動加載

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {
    if (isDropDownStyle) {
        if (currentScrollState == SCROLL_STATE_TOUCH_SCROLL
                && currentHeaderStatus != HEADER_STATUS_LOADING) {
            if (firstVisibleItem == 0) {
                headerImage.setVisibility(View.VISIBLE);
                int pointBottom = headerOriginalHeight + headerReleaseMinDistance;
                if (headerLayout.getBottom() >= pointBottom) {
                    setHeaderStatusReleaseToLoad();
                } else {
                    setHeaderStatusDropDownToLoad();
                }
            } else {
                setHeaderStatusClickToLoad();
            }
        } else if (currentScrollState == SCROLL_STATE_FLING
                && firstVisibleItem == 0
                && currentHeaderStatus != HEADER_STATUS_LOADING) {
            // 手指已離開且 header 可見,直接收起
            setSecondPositionVisible();
            hasReachedTop = true;
        } else if (currentScrollState == SCROLL_STATE_FLING && hasReachedTop) {
            setSecondPositionVisible();
        }
    }

    // 滾動到底部自動加載
    if (isOnBottomStyle && isAutoLoadOnBottom && hasMore) {
        if (firstVisibleItem > 0 && totalItemCount > 0
                && (firstVisibleItem + visibleItemCount == totalItemCount)) {
            onBottom();
        }
    }

    if (onScrollListener != null) {
        onScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
    }
}

4.5 對外暴露的關鍵方法

/** 下拉開始,切換到加載中狀態 */
public void onDropDown() {
    if (currentHeaderStatus != HEADER_STATUS_LOADING
            && isDropDownStyle && onDropDownListener != null) {
        setHeaderStatusLoading();
        onDropDownListener.onDropDown();
    }
}

/** 下拉完成,恢復狀態;secondText 顯示在 header 主文字下方 */
public void onDropDownComplete(CharSequence secondText) {
    if (isDropDownStyle) {
        setHeaderSecondText(secondText);
        onDropDownComplete();
    }
}

public void onDropDownComplete() {
    if (isDropDownStyle) {
        setHeaderStatusClickToLoad();
        if (headerLayout.getBottom() > 0) {
            invalidateViews();
            setSecondPositionVisible();
        }
    }
}

/** 底部加載完成,恢復狀態 */
public void onBottomComplete() {
    if (isOnBottomStyle) {
        if (isShowFooterProgressBar) {
            footerProgressBar.setVisibility(View.GONE);
        }
        if (!hasMore) {
            footerButton.setText(footerNoMoreText);
            footerButton.setEnabled(false);
            if (!isShowFooterWhenNoMore) {
                removeFooterView(footerLayout);
            }
        } else {
            footerButton.setText(footerDefaultText);
            footerButton.setEnabled(true);
        }
        isOnBottomLoading = false;
    }
}

/** 因 position 0 被 header 佔用,需要把第 2 個 item 滾到可見位置 */
public void setSecondPositionVisible() {
    if (getAdapter() != null && getAdapter().getCount() > 0
            && getFirstVisiblePosition() == 0) {
        setSelection(1);
    }
}

4.6 四種 Header 狀態

/** 初始狀態:可點擊觸發加載 */
public static final int HEADER_STATUS_CLICK_TO_LOAD = 1;
/** 下拉中:header 高度尚未達到閾值 */
public static final int HEADER_STATUS_DROP_DOWN_TO_LOAD = 2;
/** 已達閾值:釋放即可觸發加載 */
public static final int HEADER_STATUS_RELEASE_TO_LOAD = 3;
/** 加載中 */
public static final int HEADER_STATUS_LOADING = 4;

private void setHeaderStatusReleaseToLoad() {
    if (currentHeaderStatus != HEADER_STATUS_RELEASE_TO_LOAD) {
        headerImage.setVisibility(View.VISIBLE);
        headerImage.clearAnimation();
        headerImage.startAnimation(flipAnimation);
        headerProgressBar.setVisibility(View.GONE);
        headerText.setText(headerReleaseText);
        currentHeaderStatus = HEADER_STATUS_RELEASE_TO_LOAD;
    }
}

private void setHeaderStatusLoading() {
    if (currentHeaderStatus != HEADER_STATUS_LOADING) {
        resetHeaderPadding();
        headerImage.setVisibility(View.GONE);
        headerImage.clearAnimation();
        headerProgressBar.setVisibility(View.VISIBLE);
        headerText.setText(headerLoadingText);
        currentHeaderStatus = HEADER_STATUS_LOADING;
        setSelection(0);
    }
}

/** 根據觸摸事件調整 header 的 paddingTop,模擬橡皮筋效果 */
private void adjustHeaderPadding(MotionEvent ev) {
    int pointerCount = ev.getHistorySize();
    if (isVerticalFadingEdgeEnabled()) {
        setVerticalScrollBarEnabled(false);
    }
    for (int i = 0; i < pointerCount; i++) {
        if (currentHeaderStatus == HEADER_STATUS_DROP_DOWN_TO_LOAD
                || currentHeaderStatus == HEADER_STATUS_RELEASE_TO_LOAD) {
            headerLayout.setPadding(
                    headerLayout.getPaddingLeft(),
                    (int) (((ev.getHistoricalY(i) - actionDownPointY) - headerOriginalHeight)
                            / headerPaddingTopRate),
                    headerLayout.getPaddingRight(),
                    headerLayout.getPaddingBottom());
        }
    }
}

五、可配置項一覽

  • setOnDropDownListener() / onDropDownComplete() / onDropDownComplete(CharSequence):下拉刷新及其恢復。
  • setOnBottomListener() / onBottomComplete():底部加載及其恢復。
  • setSecondPositionVisible():在 isDropDownStyle 為 true 時,header 佔據 position 0,可能需要調用此方法讓第 2 個 item 可見(onDropDownComplete() 已默認調用)。
  • setDropDownStyle() / setOnBottomStyle() / setAutoLoadOnBottom():對應三個 XML 屬性,可運行時動態切換。
  • setHeaderPaddingTopRate():下拉距離與 paddingTop 的比例係數。
  • setHeaderReleaseMinDistance():觸發加載所需的最小釋放距離。
  • setShowFooterProgressBar():底部加載時是否顯示進度條。
  • setHasMore():是否還有更多數據,為 false 時滾到底不再觸發加載。
  • setHeaderDefaultText() / setHeaderPullText() / setHeaderReleaseText() / setHeaderLoadingText():header 四種狀態的提示文字。
  • setFooterDefaultText() / setFooterLoadingText() / setFooterNoMoreText():footer 三種狀態的提示文字。
  • setHeaderSecondText():header 的副標題文字,默認為 null(不顯示)。

所有文字與樣式都有對應的默認資源值,直接覆蓋相應的 string / color / style 即可換皮,無需改動 Java 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved