1. 程式人生 > >Android RecyclerView (四)總結(一)-(三)並且實現下拉重新整理資料,上拉載入資料功能

Android RecyclerView (四)總結(一)-(三)並且實現下拉重新整理資料,上拉載入資料功能

我們使用的程式碼還是為以前文章寫的。
這一次我們主要實現的是下拉重新整理資料,和上拉載入資料,這裡我都用Thread.sleep(xxx)的方法來模擬獲取資料等待。

首先我們下拉重新整理的時候要用到:
SwipeRefreshLayout
來看一下如何在佈局檔案中使用它:

...........
.....................  
<view
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        class="android.support.v4.widget.SwipeRefreshLayout"
android:layout_height="match_parent" > <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView> </view>

這裡可以看到我們給view設定了一個class就是android.support.v4.widget.SwipeRefreshLayout
這個元件,
接下來我們看一下程式碼部分

private SwipeRefreshLayout swipeRefreshLayout;
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //重新獲取資料
                //獲取完成swipeRefreshLayout.setRefreshing(false);
} });

這裡是我們一個下拉重新整理的實現方法,

上拉載入資料。我們通過設定監聽器的方式來實現

recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount()) {
                    swipeRefreshLayout.setRefreshing(true);

                    //分頁獲取資料
                    //獲取完成swipeRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
            }
        });

當然我們肯定要用到執行緒和Handler處理。

下面我把整個從(一)到(四)的程式碼複製出來給大家看看。

這裡我用AS建立工程的時候選擇的是Basic Activity 這樣我們可以用它的

onOptionsItemSelected 來切換佈局.

首先是 content_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.administrator.leranrecycleerview2.MainActivity"
    tools:showIn="@layout/activity_main">
    <view
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        class="android.support.v4.widget.SwipeRefreshLayout"
        android:layout_height="match_parent"
        >
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
    </view>
</RelativeLayout>

這裡主要就是一個.SwipeRefreshLayout裡面有一個RecyclerView控制元件

然後看一下 item_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:background="#ffdede"
    android:layout_margin="3dp">
<TextView
    android:id="@+id/textView"
    android:layout_width="72dp"
    android:layout_gravity="center"
    android:layout_height="wrap_content"/>
</FrameLayout >

這裡就是我們RecyclerView 的Item的一個佈局檔案。

接下來就是 menu檔案下的item_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/removeItem"
    android:title="刪除"
    app:showAsAction="never"
    ></item>
</menu>

這裡就是為我們的PopMenu設定了一個Item選項,用於長按彈出刪除選單欄。

MyAdapter

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    private List<String> infos ;
    private LayoutInflater inflater;
    public interface OnItemOnClickLisener{
        void onItemOnClickListener(View view ,int pos);
        void onItemLongOnClickListener(View view,int pos);
    }
    private OnItemOnClickLisener onClickLisener;
    public void setItemOnClickListener(OnItemOnClickLisener listener){
            this.onClickLisener=listener;
    }
    public MyAdapter(Context mContext,List<String> infos){
        this.mContext = mContext;
        this.infos = infos;
    }
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(this.mContext).inflate(R.layout.activity_item,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.getTextView().setText(infos.get(position));
        if(onClickLisener!=null){
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    onClickLisener.onItemOnClickListener(holder.itemView,pos);
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    int pos = holder.getLayoutPosition();
                    onClickLisener.onItemLongOnClickListener(holder.itemView,pos);
                    return false;
                }
            });
        }
    }
    public void removeItem(int pos){
        infos.remove(pos);
        notifyItemRemoved(pos);
    }
 public void removeAll(){

     notifyDataSetChanged();
 }
    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView  = (TextView) itemView.findViewById(R.id.textView);
        }
        public TextView getTextView(){
            return textView;
        }
    }

    public int getItemCount() {
        return infos.size();
    }
}

這個就是RecyclerView的介面卡,這裡面我們寫出了他的設定監聽器方法,並且也有我們寫好的刪除Item的函式。

接下來就是MainActivity

public class MainActivity extends AppCompatActivity {
    private RecyclerView rcView;
    private LinearLayoutManager manager;
    private MyAdapter myAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<String> info;
    Thread thread ;
    Handler handler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==2){
                info.clear();
                refreshData();
                myAdapter = new MyAdapter(MainActivity.this,info);
                rcView.setAdapter(myAdapter);
                swipeRefreshLayout.setRefreshing(false);
            }else  if(msg.what==1){
                for(int i=0;i<=10;i++)
                info.add("123");
                myAdapter = new MyAdapter(MainActivity.this,info);
                rcView.setAdapter(myAdapter);
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    };
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rcView = (RecyclerView) findViewById(R.id.recycler_view);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false);
        info = new ArrayList<String>();
        myAdapter = new MyAdapter(this,info);
        loadData();
        rcView.setLayoutManager(manager);
        rcView.setAdapter(myAdapter);
        rcView.setItemAnimator(new DefaultItemAnimator());
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary,R.color.cardview_dark_background,R.color.cardview_shadow_start_color);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {


            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            handler.sendEmptyMessage(2);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();

            }
        });
        rcView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            int lastVisibleItem;
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==myAdapter.getItemCount()){
                    swipeRefreshLayout.setRefreshing(true);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                                handler.sendEmptyMessage(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = manager.findLastVisibleItemPosition();
            }
        });
        myAdapter.setItemOnClickListener(new MyAdapter.OnItemOnClickLisener() {
            @Override
            public void onItemOnClickListener(View view, int pos) {
                Toast.makeText(MainActivity.this, "點選"+pos, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongOnClickListener(View view, int pos) {
                showPopMenu(view,pos);

            }
        });
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
    public void loadData(){
        for(int i=0;i<=15;i++){
            info.add("Item:"+i);
        }
    }
    public void refreshData(){
        for(int i=0;i<=15;i++){
            info.add("Item:");
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
       switch (id){
           case R.id.action_listView:
               manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
               rcView.setLayoutManager(manager);
               break;
           case R.id.action_gridView:
               rcView.setLayoutManager(new GridLayoutManager(this,3));
               break;
           case R.id.action_hr_gridView:
                rcView.setLayoutManager(new StaggeredGridLayoutManager(6,StaggeredGridLayoutManager.HORIZONTAL));
               break;
           case R.id.action_straggerView:

               break;

       }

        return super.onOptionsItemSelected(item);
    }
    public void showPopMenu(View view,final int pos){
        PopupMenu popupMenu = new PopupMenu(this,view);
        popupMenu.getMenuInflater().inflate(R.menu.item_menu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {

                        myAdapter.removeItem(pos);
                        return false;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                Toast.makeText(getApplicationContext(), "關閉PopupMenu", Toast.LENGTH_SHORT).show();
            }
        });
        popupMenu.show();
    }
}

這裡面的就是用了SwipeRefreshLayout來實現下拉重新整理,然後通過給RecyclerView新增setOnScrollListener來實現上拉載入。
並且我們寫了一個Menu,點選後出現選單切換manager來實現不同的佈局。並且public void showPopMenu(View view,final int pos)這個函式也實現了顯示出一個選單欄並且刪除Item的方法,然後在LongOnClickListener裡呼叫這個方法就可以了。

這個就是RecyclerView學習的整個過程,其中還有很多不足的地方,只是為了記錄一下自己的學習過程,希望大神多多提出意見,勿噴。謝謝。