Create a universal adapter!!!

Recently, listView and GridView are often used in projects. It can be said that Listview GridView is almost a necessary component in projects. Android also provides a set of mechanism to bind data for these controls, that is, Adapter
Recently, I took the time to build a universal adapter

Look at some of our previous writings:

public class ImageViewAdapter2 extends RecyclerView.Adapter<ImageViewAdapter2.MyViewHolder> {
    private SweatQuestryModel deviceDataBean;
    private Context context;
    private ArrayList<String> urls = null;
    public ImageViewAdapter2(Context context, SweatQuestryModel deviceDataBean) {
        this.context = context;
        this.deviceDataBean = deviceDataBean;
        initImageUrl(deviceDataBean);
    }

    private void initImageUrl(SweatQuestryModel deviceDataBean) {
        urls = new ArrayList<>();
        if(urls != null){
            urls.addAll(deviceDataBean.getList());
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_imageview, null);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        GlideUtil.loadNetImg2(context, holder.image, urls.get(position) , R.drawable.default_square_image);
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("imgUrls",urls);
                bundle.putInt("position", position);
                bundle.putInt("type", PictureActivity.TYPE_NET_IMG);
                ActivityUtils.showActivity(context, PictureActivity.class, bundle);
            }
        });

    }

    @Override
    public int getItemCount() {
        return deviceDataBean == null ? 0 : 9;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView image;

        public MyViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.sweat_recycler_image);
        }
    }
}

It's not bad to use this way, but we need to inherit a BaseAdapter every time, and then implement a lot of methods in it. Our most concern is the getView method every time, and the other methods are almost the same code. Can we optimize it here? Secondly, when we use Adapter, we often create a Holder to optimize performance. Each time the Holder stores a View, the operation of the Holder is nothing more than initialization, data binding and reuse. Can we also extract it here?
If we encapsulate:

/**
 * Class function description:</br>
 *v Viewholder
 * @author yuyahao
 * @version 1.0 </p> Modification time: < br > modification notes:</br>
 */
public class VolTeamAdapter extends CommonAdapter<Bean> {

    private Context context;
    public VolTeamAdapter(Context context, List<Bean> listDatas,   int layoutId) {
        super(context, listDatas, layoutId);
    }

    @Override
    protected void fillData(ViewHolder holder, int position) {
        TextView actNum = holder.getView(R.id.team_item_active_num);
        TextView time = holder.getView(R.id.team_item_time);
        TextView title = holder.getView(R.id.team_item_title);
        ImageView icon = holder.getView(R.id.team_item_icon);
        Bean item = listDatas.get(position);
        actNum.setText(String.valueOf(item.getActiveSum()) + "individual");
        time.setText(String.valueOf(item.getTimeSun()) + "h");
        title.setText(item.getName());

        GlideUtil.loadNetImgC(context,icon, item.getPhoto(), R.drawable.bg_app_title);
    }
}

Is that much easier. You can use this every time you write an adapter.

Step 1: construct BaseAdapter

**
 * Class function description:</br>
 *v Use
 * @author yuyahao
 * @version 1.0 </p> Modified:</br> Modification notes:</br>
 */
public class VolTeamAdapter extends CommonAdapter<Bean> {

    private Context context;
    public VolTeamAdapter(Context context, List<Bean> listDatas,   int layoutId) {
        super(context, listDatas, layoutId);
        this.context = context;
    }

    @Override
    protected void fillData(ViewHolder holder, int position) {
        TextView actNum = holder.getView(R.id.team_item_active_num);
        TextView time = holder.getView(R.id.team_item_time);
        TextView title = holder.getView(R.id.team_item_title);
        ImageView icon = holder.getView(R.id.team_item_icon);
        Bean item = listDatas.get(position);
        actNum.setText(String.valueOf(item.getActiveSum()) + "individual");
        time.setText(String.valueOf(item.getTimeSun()) + "h");
        title.setText(item.getName());

        GlideUtil.loadNetImgC(context,icon, item.getPhoto(), R.drawable.bg_app_title);
    }
}

All right, stop selling and go straight to the whole code.

/**
 * Class function description:</br>
 *v Viewholder
 * @author yuyahao
 * @version 1.0 </p> Modification time: < br > modification notes:</br>
 */
public abstract class CommonAdapter<T> extends BaseAdapter {
    /*** Context of context*/
    protected Context mContext;

    /*** list Data*/
    protected List<T> listDatas;

    /** Item Layout ID*/
    protected int layoutId;

    public CommonAdapter(Context context, List<T> listDatas, int layoutId) {
        this.mContext = context;
        this.listDatas = listDatas;
        this.layoutId = layoutId;
    }

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

/**
 * To get the data of the currently clicked Item
 * In onItemClick, parent.getAdapter().getItem(), get the data of the currently clicked Item
 */
    @Override
    public Object getItem(int position) {
        return listDatas.get(position);
    }

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

    /**
     *Load each Item, this method is the most critical
     */
@   Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = ViewHolder.getViewHolder(mContext, convertView,  parent, layoutId, position);
        fillData(holder, position);
        return holder.getMConvertView();
    }

    /**
     *
     * Abstract method for subclass implementation and data filling
     * @param holder
     * @param position
     */
    protected abstract void fillData(ViewHolder holder, int position);
}

The second step is the generalization of Holer

/**
 * Class function description:</br>
 *v Viewholder
 * @author yuyahao
 * @version 1.0 </p> Modification time: < br > modification notes:</br>
 */
public class ViewHolder {
    private  int mPosition;
    /**
     * View Container for the View in Holer
     * According to the Internet, it's SparseArray
     * SparseArray It is an optimization container recommended by Android, equivalent to a map < integer, View >
     */
    private SparseArray<View> mViews;

    /**
     * Item Layout View convertView
     */
    private View mConvertView;
    public ViewHolder(Context context, ViewGroup parent, int layoutId) {
        mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, null);
        mConvertView.setTag(this);
    }

    /**
     * Get ViewHolder
     * @param context
     *  context
     * @param convertView
     * @param parent
     * @param layoutId
     *            Layout layout Id
     * @param
     * @return
     */

    public static ViewHolder getViewHolder(Context context, View convertView,  ViewGroup parent, int layoutId) {
        if (convertView == null)
            return new ViewHolder(context, parent, layoutId);
        return (ViewHolder) convertView.getTag();
    }

    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
        this.mViews = new SparseArray<View>();
        this.mPosition = position;
        this.mConvertView = LayoutInflater.from(context).inflate(layoutId,
                parent, false);
        this.mConvertView.setTag(this);
    }
    /**
     * Get a ViewHolder object
     * @param context
     * @param convertView
     * @param parent
     * @param layoutId
     * @param position
     * @return
     */
    public static ViewHolder getViewHolder(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
        if (null == convertView) {
            return new ViewHolder(context, parent, layoutId, position);
        } else {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            holder.mPosition = position;
            return holder;
        }
    }
    /**
     * Get ItemView in Holder
     * @param viewId
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId) {
        View item = mViews.get(viewId);
        if (item == null) {
            item = mConvertView.findViewById(viewId);
            mViews.put(viewId, item);
        }
        return (T) item;
    }

    /** * Get convertView***/
    public View getMConvertView() {
        return mConvertView;
    }

}

This is done.

Step 3 use

/**
 * Class function description:</br>
 *v Use
 * @author yuyahao
 * @version 1.0 </p> Modification time: < br > modification notes:</br>
 */
public class VolTeamAdapter extends CommonAdapter<Bean> {

    private Context context;
    public VolTeamAdapter(Context context, List<Bean> listDatas,   int layoutId) {
        super(context, listDatas, layoutId);
        this.context = context;
    }

    @Override
    protected void fillData(ViewHolder holder, int position) {
        TextView actNum = holder.getView(R.id.team_item_active_num);
        TextView time = holder.getView(R.id.team_item_time);
        TextView title = holder.getView(R.id.team_item_title);
        ImageView icon = holder.getView(R.id.team_item_icon);
        Bean item = listDatas.get(position);
        actNum.setText(String.valueOf(item.getActiveSum()) + "");
        time.setText(String.valueOf(item.getTimeSun()) + "");
        title.setText(item.getName());

        GlideUtil.loadNetImgC(context,icon, item.getPhoto(), R.drawable.bg_app_title);
    }
}

mainActivity:

public class MyTextActivity extends BaseActivity{
    private Context cnt;
    @Bind(R.id.lv_list)
    ListView  lv_list;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addViewFillInRoot(R.layout.ctivity_mytext);
        ButterKnife.bind(this);
        cnt = this;
        initView();
    }

    private void initView() {
        try {
            List<Bean>  list = DataTest.getMyTestList();
            VolTeamAdapter volTeamAdapter = new VolTeamAdapter(cnt,list,R.layout.my_listr);
            lv_list.setAdapter(volTeamAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:gravity="center_vertical"
    android:layout_height="match_parent">
    <ImageView
        android:layout_width="@dimen/dp80"
        android:layout_height="@dimen/dp80"
        android:background="@drawable/default_head"
        android:scaleType="fitXY"
        android:id="@+id/team_item_icon"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginLeft="@dimen/dp10"
        android:orientation="vertical"
        android:layout_height="@dimen/dp80">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/team_item_title"
            android:gravity="center_vertical"
            android:layout_weight="1"
            android:text="Kakrolot"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:gravity="center_vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Heaven does not rank"
                android:id="@+id/team_item_time"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp20"
                android:text="Combat value: "

                android:id="@+id/team_item_active_num"/>

        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Design sketch:

Tags: Android xml ButterKnife encoding

Posted on Sun, 03 Nov 2019 08:47:28 -0800 by CrazeD