package com.kfzs.duanduan.utils.dlg;


import android.util.SparseArray;
import android.view.View;

/**
 * @ Created by Dlg
 * @ <p>TiTle:  ViewFindUtils</p>
 * @ <p>Description:
 * ViewHolder简洁写法,避免适配器中重复定义ViewHolder,减少代码量 用法:
 * if (convertView == null) {
 * convertView = View.inflate(context, R.layout.ad_demo, null);
 * }
 * TextView tv_demo = ViewHolderUtils.get(convertView, R.id.tv_demo);
 * ImageView iv_demo = ViewHolderUtils.get(convertView, R.id.iv_demo);
 * </p>
 * @ date:  2017/6/8 14:58
 * @ QQ:    315096953
 */

public class ViewFindUtils {
    public static <T extends View> T hold(View view, int id, Class<T> classz) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<>();
            view.setTag(viewHolder);
        }

        View childView = viewHolder.get(id);

        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }

        return (T) childView;
    }

    public static <T extends View> T hold(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<>();
            view.setTag(viewHolder);
        }

        View childView = viewHolder.get(id);

        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }

        return (T) childView;
    }

    /**
     * 替代findviewById方法
     *
     * @param view 待查的父View
     * @param id   要找查的组件id
     * @param <T>  自动匹配组件类型
     * @return
     */
    public static final  <T extends View> T find(View view, int id) {
        return (T) view.findViewById(id);
    }

    /**
     * 直接用，非赋值形式
     *
     * @param view   待查的父View
     * @param id     要找查的组件id
     * @param classz 如TextView.class
     * @param <T>    组件类型
     * @return
     */
    public static final  <T extends View> T find(View view, int id, Class<T> classz) {
        return (T) view.findViewById(id);
    }
}
