1. 程式人生 > >SwipeRefreshLayout+RecyclerView 下拉重新整理

SwipeRefreshLayout+RecyclerView 下拉重新整理

SwipeRefreshLayout 是v4包中的控制元件,
RecyclerView 是v7包中的控制元件,替代了ListView,強制使用ViewHolder。
這裡寫圖片描述

Demo 地址:https://github.com/SunnyLine/SwipeRefreshAddRecyclerView

Layout

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_refresh_widget"
android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" /> </android.support
.v4.widget.SwipeRefreshLayout>

MainActivity.class

@@ -0,0 +1,109 @@
package com.swipe.recycler;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import
android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; public class MainActivity extends AppCompatActivity { private SwipeRefreshLayout mSwipeRefreshWidget; private RecyclerView mRecyclerView; CatNamesRecyclerViewAdapter mAdapter; private String[] colors = new String[]{"#ff00ddff", "#ff99cc00", "#ffcc0000", "#ffffbb33", "#ffefefef", "#ff0099cc" , "#ffff8800", "#ffaa66cc", "#ffff4444"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget); mRecyclerView = (RecyclerView) findViewById(R.id.list); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(linearLayoutManager); mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); mAdapter = new CatNamesRecyclerViewAdapter(this); mRecyclerView.setAdapter(mAdapter); mSwipeRefreshWidget.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_purple); mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshContent(); } }); } private void refreshContent() { new Handler().postDelayed(new Runnable() { @Override public void run() { mAdapter.refreshContent(); mAdapter.notifyDataSetChanged(); mSwipeRefreshWidget.setRefreshing(false); } }, 5000); } class CatNamesRecyclerViewAdapter extends RecyclerView.Adapter<CatNamesRecyclerViewAdapter.CatNamesViewHolder> { private Context mContext; List<String> mCatNames; public CatNamesRecyclerViewAdapter(Context context) { mContext = context; mCatNames = Arrays.asList(mContext.getResources().getStringArray(R.array.day)); Collections.shuffle(mCatNames); } public class CatNamesViewHolder extends RecyclerView.ViewHolder { TextView mCatNameTextView; public CatNamesViewHolder(View itemView) { super(itemView); mCatNameTextView = (TextView) itemView.findViewById(R.id.textView); } } public void refreshContent() { Collections.shuffle(mCatNames); } @Override public CatNamesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View inflatedView = LayoutInflater.from(mContext).inflate(R.layout.item, viewGroup, false); return new CatNamesViewHolder(inflatedView); } @Override public void onBindViewHolder(CatNamesViewHolder viewHolder, int i) { String catName = mCatNames.get(i); viewHolder.mCatNameTextView.setText(catName); viewHolder.mCatNameTextView.setBackgroundColor(Color.parseColor(colors[new Random().nextInt(9)])); } @Override public int getItemCount() { return mCatNames.size(); } } }

DividerItemDecoration.class RecyclerView 設定Divider(此類是從GitHub上 下載的)

@@ -0,0 +1,128 @@
package com.swipe.recycler;

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

/**
 * This class is from the v7 samples of the Android SDK. It's not by me!
 * <p/>
 * See the license above for details.
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration
{

    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;



    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation)
    {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation)
    {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST)
        {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent)
    {
        Log.v("recyclerview - itemdecoration", "onDraw()");
         if (mOrientation == VERTICAL_LIST) {
                drawVertical(c, parent);
            } else {
                drawHorizontal(c, parent);
            }
    }

    public void drawVertical(Canvas c, RecyclerView parent)
    {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(
                    parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent)
    {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
            RecyclerView parent)
    {
        if (mOrientation == VERTICAL_LIST)
        {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}