1. 程式人生 > >ListView和RecyclerView的使用和效能優化總結

ListView和RecyclerView的使用和效能優化總結

1.ListView介紹

例如列表檢視

  在手機中,使用列表顯示是一種常見的顯示格式,那麼ListView就是一種常見的方式。例如:今日頭條,網易新聞都是使用ListView或者是最近流行的RecyclerView進行首頁的佈局,最後一節將會對它進行介紹。

2.ListView常用方法和實現邏輯介紹

2.1使用ListView

Android提供了ListView和ExpandableListView用來實現ListView這個功能。

2.2 Adapter介面卡

當你需要建立一個ListView時,需要繫結一個adapter用來實現listview中的item view資源申請和item view的資料繫結。

2.3 ListView的過濾和排序

ListView也可以實現對每一個item進行過濾或者排序,當然在開發的工程中也需要對adapter進行設計才能實現該項功能。

2.4 動態更新

notifyDataSetChanged():這個方法將在資料被改變,或者資料新建立的時候會被呼叫。這個時候你可以在這個方法中重寫方

法以至於達到動態更新資料的目的。

3.預設介面卡

3.1 預設平臺介面卡

Android提供了預設的介面卡,最主要的兩個是:ArrayAdapter和CursorAdapter。其中ArrayAdapter可基於Arrays

或java.util.List來處理資料。而SimpleCursorAdapter可以處理相關資料庫。

3.2使用ArrayAdapter的一個例子:


package com.example.zhengxie.demo_testcase;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listview);
        String[] values = new String[]{"中國移動", "中國聯通", "中國電信"};
        final ArrayList<String> arrayList = new ArrayList<String>();
        for (int i = 0; i < values.length; i++) {
            arrayList.add(values[i]);
        }
        //設定adapter(context,listview中的樣式,資料)
        final StableArrayAdapter adapter = new StableArrayAdapter(this, R.layout.rowbuttonlayout, arrayList);
        listView.setAdapter(adapter);
        //當用戶點選了一個Item時,對Item的監聽事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
                final String item = (String) parent.getItemAtPosition(position);
                view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {//對view的漸變顯示
                    @Override
                    public void run() {
                        arrayList.remove(item);
                        adapter.notifyDataSetChanged();//記:View refresh
                        view.setAlpha(1);//0為透明,1為不透明
                    }
                });
            }
        });
    }

    private class StableArrayAdapter extends ArrayAdapter<String> {
        HashMap<String, Integer> mInMap = new HashMap<String, Integer>();
        private Context context;
        private List<String> list;

        public StableArrayAdapter(Context context, int resource, List<String> objects) {
            super(context, resource, objects);
            this.context = context;
            this.list = objects;
            for (int i = 0; i < objects.size(); i++) {
                mInMap.put(objects.get(i), i);
            }
        }

        @Override
        public long getItemId(int position) {
            String item = getItem(position);
            return mInMap.get(item);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.rowbuttonlayout,null);
            final ViewHolder viewHolder ;
            if (convertView == null){//佈局快取是否為空
                viewHolder = new ViewHolder();
                viewHolder.textView = (TextView) view.findViewById(R.id.label);
                viewHolder.checkBox = (CheckBox) view.findViewById(R.id.check);
                viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        viewHolder.checkBox.setSelected(buttonView.isChecked());
                    }
                });
                view.setTag(viewHolder);//將viewHolder載入到view中
            }
            else {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.textView.setText(list.get(position));
            viewHolder.checkBox.setSelected(false);
            return view;
        }

        class ViewHolder{
            private TextView textView;
            private CheckBox checkBox;
        }
    }
}

3.3 使用ArrayActivity實現的例子


1.新建List資料集合
package com.example.zhengxie.demo_testcase;

/**
 * 
 */

public class Model {
    private String name;
    private boolean selected;

    public Model(String name) {
        this.name = name;
        selected = false;
    }

    public String getName() {
        return name;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}
2.新建ListActivity
package com.example.zhengxie.demo_testcase;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

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

/**
 * 
 */

public class MyList extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayAdapter<Model> adapter = new myArrayAdapter<Model>(this, getModel());
        setListAdapter(adapter);
    }

    private List<Model> getModel() {
        List<Model> list = new ArrayList<Model>();
        list.add(get("電信"));
        list.add(get("移動"));
        list.add(get("聯通"));
        list.get(1).setSelected(true);
        return list;
    }

    private Model get(String s) {
        return new Model(s);
    }
}
3.建立adater類:myArrayAdapter.java
package com.example.zhengxie.demo_testcase;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import java.util.List;

/**
 * 
 */
public class myArrayAdapter<T> extends ArrayAdapter<Model> {

    private final List<Model> list;
    private final Activity context;

    public myArrayAdapter(Activity context, List<Model> model) {
        super(context, R.layout.rowbuttonlayout, model);
        this.list = model;
        this.context = context;
    }

    static class ViewHolder {
        protected TextView textView;
        protected CheckBox checkBox;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.rowbuttonlayout, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.label);
            viewHolder.checkBox = (CheckBox) view.findViewById(R.id.check);
            viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (!buttonView.isPressed()) return;
                    Model element = (Model) viewHolder.checkBox.getTag();
                    element.setSelected(buttonView.isChecked());
                }
            });
            view.setTag(viewHolder);
            viewHolder.checkBox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkBox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.textView.setText(list.get(position).getName());
        holder.checkBox.setChecked(list.get(position).isSelected());
        return view;
    }
}

4.RecyclerView

上面介紹完了ListView的常用顯示方式和技巧。下面進行一個當前最火的RecyclerView,這個實現類擁有著很多有點,

基本解決了ListView的一些缺陷,比如:需要手動重寫ViewHolder,對於item的動畫操作也需要很複雜的邏輯去實現等等。

下面我將用自己實現的一個例項為大家介紹:


1.新建RecyclerView的xml資源:
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.example.zhengxie.recyclerview.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rw_main"
        android:layout_width="match_parent"
        android:layout_centerHorizontal="true"
        android:background="#000000"
        android:layout_height="wrap_content"
        >
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>
2.新建類,對於RecyclerView進行初始化:
package com.example.zhengxie.recyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.animation.Animation;

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MyAdapter mMyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //第一步:宣告RecyclerView
        mRecyclerView = (RecyclerView) findViewById(R.id.rw_main);
        //第二步:設定佈局的格式:LinearLayoutManager是水平顯示(如果要建立一個自定義佈局管理器,請擴充套件 RecyclerView.LayoutManager 類別)
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //第三步:宣告一個Adapter
        mMyAdapter = new MyAdapter(this, initData());
        //繫結一個自定義的分割線
        mRecyclerView.addItemDecoration(new MyItemDivider(this,R.drawable.shape));
        //第四步:繫結adapter
        mRecyclerView.setAdapter(mMyAdapter);
    }

    //第五步:宣告一個ArrayList陣列儲存資料
    private List<String> initData() {
        List<String> datas = new ArrayList<>();
        for (int i = 0; i <= 40; i++) {
            datas.add("Item:"+i);
        }
        return datas;
    }
}
3.初始化adapter:MyAdapter.java類

package com.example.zhengxie.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * 
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private List<String> datas;
    private LayoutInflater inflater;

    //第一步:建立建構函式需要的引數
    public MyAdapter(Context context, List<String> datas) {
        this.datas = datas;
        //記第二步:初始化inflate
        inflater = LayoutInflater.from(context);
    }

    //第三步:宣告MyViewHolder這個類,初始化每個資源
    public class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView title;

        //第五步:宣告每個item
        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.rv_main_item_title);
        }
    }

    //第四步:重寫createView
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.rv_main_item, parent, false));
        return holder;
    }

    //第六步:這裡對資料進行賦值操作
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.title.setText(datas.get(position));
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }
}
4.新增一個Decoratoin的shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:centerColor="#FF00FF00"
        android:endColor="#FF0000FF"
        android:startColor="#FFFF0000"
        android:type="linear"
        >
    </gradient>
    <size
        android:height="1dp">

    </size>
</shape>
5.新增addItemDecoration類:MyItemDivider.java
package com.example.zhengxie.recyclerview;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * 
 */

public class MyItemDivider extends RecyclerView.ItemDecoration{
    private Drawable mDrawable;

    public MyItemDivider(Context context, int resId) {
        mDrawable = context.getResources().getDrawable(resId);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();//左邊距
        int right = parent.getWidth() - parent.getPaddingRight();//右邊距
        int childCount = parent.getChildCount();//獲得當前首次重新整理時頁面的item個數
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + params.bottomMargin;//獲得要畫decoration的上高度
            int bottom = top + mDrawable.getIntrinsicHeight();//獲得要畫decoration下高度
            mDrawable.setBounds(left, top, right, bottom);
            mDrawable.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.set(0,0,0,mDrawable.getIntrinsicWidth());
    }
}

5.附加

對於RecyclerView中實現的Drawable的left,top,right,botton這裡做一下說明:


這樣大家就更容易更方便的理解Drawable方法在Android系統裡的繪製圖片的模式和座標位置了。