先声明一下ViewHolder在Android自定义的适配器中使用。目的:优化资源,节省空间,避免重复绘制view而引起的不必要的内存损耗。

我自己以前的写法:

public class PlateAdapter extends BaseAdapter {private List<Plate> list;private Context context;public PlateAdapter(List<Plate> list, Context context) {super();this.list = list;this.context = context;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn list.get(arg0);}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic View getView(int arg0, View arg1, ViewGroup arg2) {// TODO Auto-generated method stubif(arg1 == null){arg1 = LayoutInflater.from(context).inflate(R.layout.select_car_type_list_item, null);}TextView text = (TextView)arg1.findViewById(R.id.text);text.setText(list.get(arg0).getPlateType());return arg1;}}
学习过ViewHolder之后的写法:

@SuppressWarnings("unused")public class NoticeAdapter  extends BaseAdapter{private Context _context;private List<ExamNotice> _list;public NoticeAdapter(Context context, List<ExamNotice> list) {super();this._context = context;this._list = list;}public void set_list(List<ExamNotice> _list) {this._list = _list;}@Overridepublic int getCount() {return _list.size();}@Overridepublic Object getItem(int arg0) {return _list.get(arg0);}@Overridepublic long getItemId(int arg0) {return arg0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {Holder holder;if(null==convertView){convertView=View.inflate(_context, R.layout.notice_item, null);holder=new Holder();holder.studyPlanName=(TextView)convertView.findViewById(R.id.xxjh_item_name);holder.studyPlanDate=(TextView)convertView.findViewById(R.id.xxjh_item_date);convertView.setTag(holder);}else{holder=(Holder)convertView.getTag();}ExamNotice notice=(ExamNotice) getItem(position);holder.studyPlanName.setText(notice.getNoticeTitle());SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String noticeDate = sdf.format(notice.getNoticeDate());holder.studyPlanDate.setText(noticeDate);return convertView;}private static class Holder{public TextView studyPlanName,studyPlanDate;}}

看一下官方的API:

/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.example.android.apis.view;import android.app.ListActivity;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;import android.widget.ImageView;import android.graphics.BitmapFactory;import android.graphics.Bitmap;import com.example.android.apis.R;/** * Demonstrates how to write an efficient list adapter. The adapter used in this example binds * to an ImageView and to a TextView for each row in the list. * * To work efficiently the adapter implemented here uses two techniques: * - It reuses the convertView passed to getView() to avoid inflating View when it is not necessary * - It uses the ViewHolder pattern to avoid calling findViewById() when it is not necessary * * The ViewHolder pattern consists in storing a data structure in the tag of the view returned by * getView(). This data structures contains references to the views we want to bind data to, thus * avoiding calls to findViewById() every time getView() is invoked. */public class List14 extends ListActivity {    private static class EfficientAdapter extends BaseAdapter {        private LayoutInflater mInflater;        private Bitmap mIcon1;        private Bitmap mIcon2;        public EfficientAdapter(Context context) {            // Cache the LayoutInflate to avoid asking for a new one each time.            mInflater = LayoutInflater.from(context);            // Icons bound to the rows.            mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);            mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);        }        /**         * The number of items in the list is determined by the number of speeches         * in our array.         *         * @see android.widget.ListAdapter#getCount()         */        public int getCount() {            return DATA.length;        }        /**         * Since the data comes from an array, just returning the index is         * sufficent to get at the data. If we were using a more complex data         * structure, we would return whatever object represents one row in the         * list.         *         * @see android.widget.ListAdapter#getItem(int)         */        public Object getItem(int position) {            return position;        }        /**         * Use the array index as a unique id.         *         * @see android.widget.ListAdapter#getItemId(int)         */        public long getItemId(int position) {            return position;        }        /**         * Make a view to hold each row.         *         * @see android.widget.ListAdapter#getView(int, android.view.View,         *      android.view.ViewGroup)         */        public View getView(int position, View convertView, ViewGroup parent) {            // A ViewHolder keeps references to children views to avoid unneccessary calls            // to findViewById() on each row.            ViewHolder holder;            // When convertView is not null, we can reuse it directly, there is no need            // to reinflate it. We only inflate a new View when the convertView supplied            // by ListView is null.            if (convertView == null) {                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);                // Creates a ViewHolder and store references to the two children views                // we want to bind data to.                holder = new ViewHolder();                holder.text = (TextView) convertView.findViewById(R.id.text);                holder.icon = (ImageView) convertView.findViewById(R.id.icon);                convertView.setTag(holder);            } else {                // Get the ViewHolder back to get fast access to the TextView                // and the ImageView.                holder = (ViewHolder) convertView.getTag();            }            // Bind the data efficiently with the holder.            holder.text.setText(DATA[position]);            holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);            return convertView;        }        static class ViewHolder {            TextView text;            ImageView icon;        }    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setListAdapter(new EfficientAdapter(this));    }    private static final String[] DATA = Cheeses.sCheeseStrings;}

更多相关文章

  1. Android在listview添加checkbox实现原理与代码
  2. 使用Bmob时遇到的Android依赖包冲突(Gson、Okhttp)
  3. Android中GridView的每行自动适应Adapter的个数
  4. 【Android(安卓)基础】 ListView 部分Item不可选中
  5. WebView 知识点
  6. Android(安卓)OpenGL ES(九):绘制线段Line Segment
  7. UI-TextView省略号
  8. Android(安卓)按压效果的工具类
  9. Android中fragment+viewpager实现布局

随机推荐

  1. Androidの异常总结
  2. android 呼入电话的监听(来电监听)转
  3. android自带Base64加密解密
  4. 全志A64 Android7.1屏蔽使用按键进入安全
  5. android应用中去掉标题栏的方法
  6. Android下如何防止横竖屏切换的时候进度
  7. Linux 命令行更新指定版本 android sdk
  8. 修改应用按键无响应的时间
  9. Installation error: INSTALL_FAILED_VER
  10. Android 开源项目