Java泛型应用之打造Android的万能ViewHolder

Cin61O 8年前
   <h2><strong>在ListView的Adapter中的getView()方法中的繁琐写法</strong></h2>    <pre>  <code class="language-java">@Override    public View getView(int position, View convertView, ViewGroup parent) {        ViewHolder viewHolder = null;      if (convertView == null) {            convertView = LayoutInflater.from(context)              .inflate(R.layout.item, parent, false);              viewHolder = new ViewHolder();            viewHolder.name = (TextView) convertView.findViewById(R.id.name);             convertView.setTag(viewHolder);      }else{              viewHolder = (ViewHolder) convertView.getTag();          }      viewHolder.name.setText("sss");         return convertView;    }    private static class ViewHolder      {          TextView name;      }</code></pre>    <h2><strong>先了解一下SparseArray</strong></h2>    <p>SparseArray(稀疏数组).他是Android内部特有的api,标准的jdk是没有这个类的.在Android内部用来替代HashMap<Integer,E>这种形式,使用SparseArray更加节省内存空间的使用,SparseArray也是以key和value对数据进行保存的.使用的时候只需要指定value的类型即可.并且key不需要封装成对象类型.</p>    <h2><strong>最后经过优化和简化后的代码</strong></h2>    <ul>     <li>代码</li>    </ul>    <pre>  <code class="language-java">/**   * Created by yuandl on 2016-10-13.   */    import android.util.SparseArray;  import android.view.View;    /**   * 万能的ViewHolder   *   * @author   */  public class CommonViewHolder {      /**       * @param view 所有缓存View的根View       * @param id   缓存View的唯一标识       * @return       */      public static <T extends View> T get(View view, int id) {            SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();          //如果根view没有用来缓存View的集合          if (viewHolder == null) {              viewHolder = new SparseArray<View>();              view.setTag(viewHolder);//创建集合和根View关联          }          View chidlView = viewHolder.get(id);//获取根View储存在集合中的孩纸          if (chidlView == null) {//如果没有改孩纸              //找到该孩纸              chidlView = view.findViewById(id);              viewHolder.put(id, chidlView);//保存到集合          }          return (T) chidlView;      }  }</code></pre>    <ul>     <li> <p>用法(可以看到省去了好多代码)</p> <pre>  <code class="language-java">@Override    public View getView(int position, View convertView, ViewGroup parent) {       if (convertView == null) {         convertView = LayoutInflater.from(context)           .inflate(R.layout.item, parent, false);     }       TextView name= ViewHolder.get(convertView, R.id.name);       name.setText("sss");       return convertView;    }</code></pre> </li>    </ul>    <p> </p>    <p>来自:http://www.jianshu.com/p/43d5994e55b6</p>    <p> </p>