Android BaseAdapter使用詳解 – Android移動開發技術文章_手機開發 Android移動開發教學課程

類概述
BaseAdapter主要用於ListView(實現指定的ListAdapter接口)、Spinner(實現指定的SpinnerAdapter接口)以及GridView的共同實現一個公共基類適配器。
假設我們實現一個ArrayListAdapter,
public abstract class ArrayListAdapter<T> extends BaseAdapter{
       
        protected ArrayList<T> mList;
        protected Activity mContext;
        protected ListView mListView;
       
        public ArrayListAdapter(Activity context){
                this.mContext = context;
        }


        @Override
        //設置像layout中填充的條目數量
        public int getCount() {
                if(mList != null)
                        return mList.size();
                else
                        return 0;
        }


        @Override
        public Object getItem(int position) {
                return mList == null ? null : mList.get(position);
        }


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


        @Override
    /**
     * @param position      position就是位置從0開始
     * @param convertView   convertView是Spinner,ListView中每一項要顯示的view
     * @param parent        parent就是父窗體瞭,也就是Spinner,ListView,GridView瞭
     * @return              通常return 的view也就是convertView
     * 繪制的內容均在此實現
     */
        abstract public View getView(int position, View convertView, ViewGroup parent);
       
        public void setList(ArrayList<T> list){
                this.mList = list;
                notifyDataSetChanged();
        }
       
        public ArrayList<T> getList(){
                return mList;
        }
       
        public void setList(T[] list){
                ArrayList<T> arrayList = new ArrayList<T>(list.length);   
                for (T t : list) {   
                        arrayList.add(t);   
                }   
                setList(arrayList);
        }
       
        public ListView getListView(){
                return mListView;
        }
       
        public void setListView(ListView listView){
                mListView = listView;
        }


}

You May Also Like