《Android進階之光》RecyclerView 使用完全解析

跟着《Android進階之光》複習下RecyclerView。

重要的幾點:

  • 你想要控制其顯示的方式,請通過佈局管理器LayoutManager
  • 你想要控制Item間的間隔(可繪製),請通過ItemDecoration
  • 你想要控制Item增刪的動畫,請通過ItemAnimator
  • 你想要控制點擊、長按事件,請自己寫

先來效果圖:

 

然後上代碼!!!

activity:

public class RecyclerViewActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView recyclerView;
    private List<String> dataList;
    private int dataSize = 20;
    private Button btnAddItem;
    private Button btnRemoveTerm;
    private MyAdapter adapter;

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

        initView();
    }

    private void initView() {

        //list增刪item的按鈕
        btnAddItem = findViewById(R.id.btn_addTerm);
        btnRemoveTerm = findViewById(R.id.btn_removeTerm);

        btnAddItem.setOnClickListener(this);
        btnRemoveTerm.setOnClickListener(this);

        //拿到recyclerView
        recyclerView = findViewById(R.id.recyclerView);

        //設置佈局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));

        //設置item增刪時的動畫
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //添加裝飾(DividerItemDecoration是添加分割線,分割線的樣式也可自定義)
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        //初始化數據
        dataList = new ArrayList<>();
        for (int i = 0; i < dataSize; i++) {
            dataList.add("hehe" + i);
        }

        //創建適配器
        adapter = new MyAdapter(this, dataList);

        //通過適配器設置item點擊事件
        adapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int tag) {
                Toast.makeText(RecyclerViewActivity.this, "點了,位置:"+ tag, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View v, int tag) {
                Toast.makeText(RecyclerViewActivity.this, "長按了,位置:"+ tag, Toast.LENGTH_SHORT).show();
            }
        });

        //設置適配器
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_addTerm:
//                adapter.addData(1, "addItem");
                adapter.addDataWithAnimator(1, "addItemWithAnimator");

                break;
            case R.id.btn_removeTerm:
//                adapter.removeData(1);
                adapter.removeDataWithAnimator(2);
                break;
            default:
                break;
        }
    }


    /**
     * 自定義的適配器
     */
    private static class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements View.OnClickListener, View.OnLongClickListener {

        private final Context context;

        //要展示的數據
        private final List<String> dataList;

        private OnItemClickListener mOnItemClickListener;

        public MyAdapter(Context context, List<String> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //加載Item佈局,然後創建ViewHolder
            View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_item, parent, false);
            //設置監聽
            view.setOnClickListener(this);
            view.setOnLongClickListener(this);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            //視圖綁定數據
            holder.textView.setText(dataList.get(position));
            //position設置給itemView的Tag
            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }

        /**
         * 提供使用 adapter給item設置點擊監聽事件
         * @param onItemClickListener
         */
        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }

        @Override
        public void onClick(View v) {
            if(mOnItemClickListener != null){
                mOnItemClickListener.onItemClick(v, (int)v.getTag());
            }
        }

        @Override
        public boolean onLongClick(View v) {
            if(mOnItemClickListener != null){
                mOnItemClickListener.onItemLongClick(v, (int)v.getTag());
            }
            return true;
        }

        //添加數據
        public void addData(int position, String data){
            if (dataList != null) {
                dataList.add(position, data);
                //刷新
                notifyDataSetChanged();
            }
        }

        //添加數據with動畫
        public void addDataWithAnimator(int position, String addItem) {
            if (dataList != null) {
                dataList.add(position, addItem);
                notifyItemInserted(position);
            }
        }

        //刪除數據
        public void removeData(int position){
            if (dataList != null) {
                if ((dataList.size() > position )) {
                    dataList.remove(position);
                    //刷新
                    notifyDataSetChanged();
                }else {
                    Toast.makeText(context, "長度不夠!", Toast.LENGTH_SHORT).show();
                }
            }
        }

        //刪除數據with動畫
        public void removeDataWithAnimator(int position){
            if (dataList != null) {
                if ((dataList.size() > position )) {
                    dataList.remove(position);
                    //刷新
                    notifyItemRemoved(position);
                }else {
                    Toast.makeText(context, "長度不夠!", Toast.LENGTH_SHORT).show();
                }
            }
        }


        //viewHolder
        public class MyViewHolder extends RecyclerView.ViewHolder {

            private final TextView textView;

            public MyViewHolder(View itemView) {
                super(itemView);
                textView = (TextView) itemView.findViewById(R.id.tv_item);
            }
        }

        /**
         * Item點擊事件接口,由activity實現
         */
        public interface OnItemClickListener {

            void onItemClick(View v, int tag);

            void onItemLongClick(View v, int tag);
        }
    }


}

 

activity的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_addTerm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="add"/>
    <Button
        android:id="@+id/btn_removeTerm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="remove"/>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="64dp">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

 

item的xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@color/colorAccent"/>

</android.support.constraint.ConstraintLayout>

 

分割線的自定義:

styles.xml中:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <!--recyclerView的自定義的分割線的樣式-->
        <item name="android:listDivider">@drawable/bg_recyclerview_divider</item>
    </style>

</resources>

drawable文件夾:

<?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"/>

    <size
        android:width="10dp"
        android:height="10dp"/>

</shape>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章