1. 程式人生 > >[Android] Android RecycleView和ListView 自定義Adapter封裝類

[Android] Android RecycleView和ListView 自定義Adapter封裝類

draw ger settag 位置 visible com ppr trac end

在網上查看了很多對應 Android RecycleView和ListView 自定義Adapter封裝 的文章,主要存在幾個問題:

一)、網上代碼一大抄,復制來復制去,大部分都運行不起來,或者 格式錯亂

二)、剩下的那些能運行起來的,將Adapter類、ViewHolder類,放在不同文件裏,導致文件多、雜

於是總結這兩個單獨的Custom***ViewAdapter 類,以方便調用!

一、RecycleView Adapter自定義封裝類

CustomRecyclerViewAdapter.java
package com.jack.androidbase.adapter;

import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List;
public abstract class CustomRecyclerViewAdapter<T> extends RecyclerView.Adapter<CustomRecyclerViewAdapter.ViewHolder> { private int mLayoutRes; private List<T> mData; //定義接口 OnItemClickListener public interface OnItemClickListener { void onItemClick(View view, int
position); void onItemLongClick(View view, int position); } private OnItemClickListener mOnItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { mOnItemClickListener = onItemClickListener; } public CustomRecyclerViewAdapter(List<T> mData, int mLayoutRes) { this.mLayoutRes = mLayoutRes; this.mData = mData; } /** * inflate操作 */ @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ViewHolder viewHolder = ViewHolder.get(parent.getContext(), parent, mLayoutRes); return viewHolder; } /** * 暴露出來的接口 * * @param holder * @param obj */ public abstract void bindView(ViewHolder holder, T obj); @Override public void onBindViewHolder(final ViewHolder holder, int position) { bindView(holder, mData.get(position)); //綁定事件 if (mOnItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickListener.onItemClick(holder.itemView, pos); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickListener.onItemLongClick(holder.itemView, pos); return false; } }); } } /** * 獲取高度 * * @return */ @Override public int getItemCount() { if (mData == null) { return 0; } return mData.size(); } /** * ViewHolder */ public static class ViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; private View mConvertView; public ViewHolder(Context context, View itemView, ViewGroup parent) { super(itemView); mConvertView = itemView; mViews = new SparseArray<View>(); } public static ViewHolder get(Context context, ViewGroup parent, int layoutid) { View itemView = LayoutInflater.from(context).inflate(layoutid, parent, false); ViewHolder holder = new ViewHolder(context, itemView, parent); return holder; } public <T extends View> T getView(int viewid) { View view = mViews.get(viewid); if (view == null) { view = mConvertView.findViewById(viewid); mViews.put(viewid, view); } return (T) view; } /** * 設置TextView文本 */ public ViewHolder setText(int viewId, CharSequence text) { View view = getView(viewId); if (view instanceof TextView) { ((TextView) view).setText(text); } return this; } /** * 設置View的Visibility */ public ViewHolder setViewVisibility(int viewId, int visibility) { getView(viewId).setVisibility(visibility); return this; } /** * 設置ImageView的資源 */ public ViewHolder setImageResource(int viewId, int drawableRes) { View view = getView(viewId); if (view instanceof ImageView) { ((ImageView) view).setImageResource(drawableRes); } else { view.setBackgroundResource(drawableRes); } return this; } } }

如何使用:

MainActivity.java 調用

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

        bindView();
    }

    private void bindView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.ui_basic_recycler_custom_1);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mData = new ArrayList();
        for (int i = 0; i < 10; i++) {
            mData.add("" + i);
        }

        //數據裝載
        myAdapter = new CustomRecyclerViewAdapter(mData, R.layout.item_recyler_1) {
            @Override
            public void bindView(ViewHolder holder, Object obj) {
                holder.setText(R.id.recycler_txt_1, obj.toString());
            }
        };

        //點擊監聽
        listener1 = new CustomRecyclerViewAdapter.OnItemClickListener(){
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(getApplicationContext(), position + " click", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(getApplicationContext(), position + " Long click", Toast.LENGTH_SHORT).show();
            }
        };
        mRecyclerView.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(listener1);
    }



activity_ui_recycler_view2.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".activity.***Activity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/ui_basic_recycler_custom_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>
</RelativeLayout>

二、ListView Adapter 自定義封裝類

CustomListViewAdapter.java
package com.jack.androidbase.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jack.androidbase.R;

import java.util.ArrayList;
import java.util.LinkedList;

public abstract class CustomListViewAdapter<T> extends BaseAdapter {

    private ArrayList<T> mData;
    private int mLayoutRes;           //布局id

    public CustomListViewAdapter(ArrayList<T> mData, int mLayoutRes) {
        this.mData = mData;
        this.mLayoutRes = mLayoutRes;
    }

    @Override
    public int getCount() {
        return mData != null ? mData.size() : 0;
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = ViewHolder.bind(parent.getContext(), convertView, parent, mLayoutRes
                , position);
        bindView(holder, getItem(position));
        return holder.getItemView();
    }

    public abstract void bindView(ViewHolder holder, T obj);

    //添加一個元素
    public void add(T data) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(data);
        notifyDataSetChanged();
    }

    //往特定位置,添加一個元素
    public void add(int position, T data) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(position, data);
        notifyDataSetChanged();
    }

    public void remove(T data) {
        if (mData != null) {
            mData.remove(data);
        }
        notifyDataSetChanged();
    }

    public void remove(int position) {
        if (mData != null) {
            mData.remove(position);
        }
        notifyDataSetChanged();
    }

    public void clear() {
        if (mData != null) {
            mData.clear();
        }
        notifyDataSetChanged();
    }

    public static class ViewHolder {

        private SparseArray<View> mViews;   //存儲ListView 的 item中的View
        private View item;                  //存放convertView
        private int position;               //遊標
        private Context context;            //Context上下文

        //構造方法,完成相關初始化
        private ViewHolder(Context context, ViewGroup parent, int layoutRes) {
            mViews = new SparseArray<>();
            this.context = context;
            View convertView = LayoutInflater.from(context).inflate(layoutRes, parent, false);
            convertView.setTag(this);
            item = convertView;
        }

        //綁定ViewHolder與item
        public static ViewHolder bind(Context context, View convertView, ViewGroup parent,
                                      int layoutRes, int position) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder(context, parent, layoutRes);
            } else {
                holder = (ViewHolder) convertView.getTag();
                holder.item = convertView;
            }
            holder.position = position;
            return holder;
        }

        @SuppressWarnings("unchecked")
        public <T extends View> T getView(int id) {
            T t = (T) mViews.get(id);
            if (t == null) {
                t = (T) item.findViewById(id);
                mViews.put(id, t);
            }
            return t;
        }


        /**
         * 獲取當前條目
         */
        public View getItemView() {
            return item;
        }

        /**
         * 獲取條目位置
         */
        public int getItemPosition() {
            return position;
        }

        /**
         * 設置文字
         */
        public ViewHolder setText(int id, CharSequence text) {
            View view = getView(id);
            if (view instanceof TextView) {
                ((TextView) view).setText(text);
            }
            return this;
        }

        /**
         * 設置圖片
         */
        public ViewHolder setImageResource(int id, int drawableRes) {
            View view = getView(id);
            if (view instanceof ImageView) {
                ((ImageView) view).setImageResource(drawableRes);
            } else {
                view.setBackgroundResource(drawableRes);
            }
            return this;
        }


        /**
         * 設置點擊監聽
         */
        public ViewHolder setOnClickListener(int id, View.OnClickListener listener) {
            getView(id).setOnClickListener(listener);
            return this;
        }

        /**
         * 設置可見
         */
        public ViewHolder setVisibility(int id, int visible) {
            getView(id).setVisibility(visible);
            return this;
        }

        /**
         * 設置標簽
         */
        public ViewHolder setTag(int id, Object obj) {
            getView(id).setTag(obj);
            return this;
        }

        //其他方法可自行擴展

    }

}

如何使用:

MainActivity.java 調用

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

        mContext = UIBaseListViewCustomActivity.this;
        initList();
    }

    private void initList() {
        list_book = (ListView) findViewById(R.id.ui_base_list_v2_1);

        //數據初始化
        mData1 = new ArrayList<>();
        mData1.add(new Animal("狗說", "你是狗麽?", R.drawable.avatar_1));
        mData1.add(new Animal("牛說", "你是牛麽?", R.drawable.avatar_2));
        mData1.add(new Animal("鴨說", "你是鴨麽?", R.drawable.avatar_3));

        //Adapter初始化
        myAdapter1 = new CustomListViewAdapter<Animal>((ArrayList) mData1, R.layout.item_list_animal) {
            @Override
            public void bindView(ViewHolder holder, Animal obj) {
                holder.setImageResource(R.id.img_icon, obj.getaIcon());
                holder.setText(R.id.txt_aName, obj.getaName());
            }
        };

        //ListView設置下Adapter:
        list_book.setAdapter(myAdapter1);
        
        list_book.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(mContext, "你點擊了~" + position + "~項", Toast.LENGTH_SHORT).show();
            }
        });
    }

item_list_animal 布局文件 :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".activity.UIBaseListViewActivity">

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:baselineAlignBottom="true"
        android:paddingLeft="8dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingTop="10dp">

        <TextView
            android:id="@+id/txt_aName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#1D1D1C"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/txt_aSpeak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#B4B4B9"
            android:textSize="14sp" />

    </LinearLayout>

</LinearLayout>

三、Github倉庫代碼:

Github:

https://github.com/wukong1688/AndroidBase/tree/master/app/src/main/java/com/jack/androidbase/adapter

如果對您有幫助,歡迎 點贊,歡迎Star,並轉發!

本博客地址: wukong1688

本文原文地址: https://www.cnblogs.com/wukong1688/p/10661391.html

轉載請著名出處!謝謝~~

[Android] Android RecycleView和ListView 自定義Adapter封裝類