ListView的使用

2016-03-29  本文已影响0人  上善若水Ryder

简介

Adapter

提供哪些Adapter

何时使用BaseAdapter

Adapter的执行

优化

容易出现的Exception

补充

实例代码(使用getViewTypeCount和getItemViewType)

package com.cienet.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.cienet.android.adapter.FourAdapter;

import java.util.ArrayList;
import java.util.HashMap;

public class FourActivity extends Activity {

    private ListView mListView;
    private MyAdapter mAdapter;
    private ArrayList<HashMap<String, Object>> mList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(R.id.lv);

        getDate();

        mAdapter = new MyAdapter(this, mList);
        //为ListView绑定适配器
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
    }

    private void getDate() {
        ArrayList<HashMap<String, Object>> listItem =
                new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("province", "江苏省");
        map.put("type", 0);
        listItem.add(map);

        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("city", "南京市");
        map1.put("type", 1);
        listItem.add(map1);

        HashMap<String, Object> map8 = new HashMap<String, Object>();
        map8.put("city", "镇江市");
        map8.put("type", 1);
        listItem.add(map8);

        HashMap<String, Object> map2 = new HashMap<String, Object>();
        map2.put("province", "浙江省");
        map2.put("type", 0);
        listItem.add(map2);

        HashMap<String, Object> map3 = new HashMap<String, Object>();
        map3.put("city", "宁波市");
        map3.put("type", 1);
        listItem.add(map3);

        HashMap<String, Object> map4 = new HashMap<String, Object>();
        map4.put("province", "山东省");
        map4.put("type", 0);
        listItem.add(map4);

        HashMap<String, Object> map5 = new HashMap<String, Object>();
        map5.put("city", "济南市");
        map5.put("type", 1);
        listItem.add(map5);

        HashMap<String, Object> map6 = new HashMap<String, Object>();
        map6.put("province", "安徽省");
        map6.put("type", 0);
        listItem.add(map6);

        HashMap<String, Object> map7 = new HashMap<String, Object>();
        map7.put("city", "合肥市");
        map7.put("type", 1);
        listItem.add(map7);

        mList = listItem;
    }
}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/item_province_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/item_city_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"/>
</RelativeLayout>

package com.cienet.android.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cienet.android.R;

public class MyAdapter extends BaseAdapter {
    public static final int ITEM_TITLE = 0;
    public static final int ITEM_INTRODUCE = 1;
    private ArrayList<HashMap<String, Object>> mList;
    private Context context;

    private LayoutInflater inflater;

    public MyAdapter(Context context, ArrayList<HashMap<String, Object>> mList) {
        this.context = context;
        this.mList = mList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        System.out.println("mList.size()" + mList.size());
        return mList.size();
    }

    @Override
    public Object getItem(int arg0) {
        return mList.get(arg0);
    }

    @Override
    public int getItemViewType(int position) {
        return (Integer) mList.get(position).get("type");
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        FirstHolder firstHolder = null;
        SecondHolder secondHolder = null;
        if (convertView == null) {
            switch (type) {
                case ITEM_TITLE:
                    convertView = inflater.inflate(R.layout.item_province, null);
                    firstHolder = new FirstHolder(convertView);
                    firstHolder.provinceTitle.setText(mList.get(position).get("province").toString());
                    convertView.setTag(firstHolder);
                    break;
                case ITEM_INTRODUCE:
                    convertView = inflater.inflate(R.layout.item_city, null);
                    secondHolder = new SecondHolder(convertView);
                    secondHolder.cityTitle.setText(mList.get(position).get("city").toString());
                    convertView.setTag(secondHolder);
                    break;
                default:
                    break;
            }
        } else {
            switch (type) {
                case ITEM_TITLE:
                    firstHolder = (FirstHolder) convertView.getTag();
                    firstHolder.provinceTitle.setText(mList.get(position).get("province").toString());
                    break;
                case ITEM_INTRODUCE:
                    secondHolder = (SecondHolder) convertView.getTag();
                    secondHolder.cityTitle.setText(mList.get(position).get("city").toString());
                    break;

                default:
                    break;
            }
        }

        return convertView;
    }

    class FirstHolder {
        TextView provinceTitle;

        FirstHolder(View view) {
            provinceTitle = (TextView) view.findViewById(R.id.item_province_text);
        }
    }

    class SecondHolder {
        TextView cityTitle;

        SecondHolder(View view) {
            cityTitle = (TextView) view.findViewById(R.id.item_city_text);
        }
    }
}

阅读ListView源代码

    class AdapterDataSetObserver extends DataSetObserver {

        private Parcelable mInstanceState = null;

        @Override
        public void onChanged() {
            mDataChanged = true;
            mOldItemCount = mItemCount;
            mItemCount = getAdapter().getCount();

            // Detect the case where a cursor that was previously invalidated has
            // been repopulated with new data.
            if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null
                    && mOldItemCount == 0 && mItemCount > 0) {
                AdapterView.this.onRestoreInstanceState(mInstanceState);
                mInstanceState = null;
            } else {
                rememberSyncState();
            }
            checkFocus();
            requestLayout();
        }

        @Override
        public void onInvalidated() {
            mDataChanged = true;

            if (AdapterView.this.getAdapter().hasStableIds()) {
                // Remember the current state for the case where our hosting activity is being
                // stopped and later restarted
                mInstanceState = AdapterView.this.onSaveInstanceState();
            }

            // Data is invalid so we should reset our state
            mOldItemCount = mItemCount;
            mItemCount = 0;
            mSelectedPosition = INVALID_POSITION;
            mSelectedRowId = INVALID_ROW_ID;
            mNextSelectedPosition = INVALID_POSITION;
            mNextSelectedRowId = INVALID_ROW_ID;
            mNeedSync = false;

            checkFocus();
            requestLayout();
        }

        public void clearSavedState() {
            mInstanceState = null;
        }
    }
* 看了这段代码,可以看出调用notifyDataSetChanged()跟调用notifyDataSetInvalidated()两者之间的区别。
* 运用了一种设计模式:观察者设计模式。借此可以学习或者巩固这一设计模式。
* AdapterView之所以能对Adapter的数据更新进行响应,原因就是在Adapter上注册了一个数据观察者(AdapterDataSetObserver)的内部类,所以,我们只要对Adpater状态的改变发送一个通知,就可以让AdapterView调用相应的方法。
* 查看AdapterDataSetObserver内部类的父类DataSetObservable。
* 对比onChange()与onInvalidated()两个方法,前者会对当前位置的状态进行同步,后者会重置所有位置的状态。
    /**
     * Get the position within the adapter's data set for the view, where view is a an adapter item
     * or a descendant of an adapter item.
     *
     * @param view an adapter item, or a descendant of an adapter item. This must be visible in this
     *        AdapterView at the time of the call.
     * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION}
     *         if the view does not correspond to a list item (or it is not currently visible).
     */
    public int getPositionForView(View view) {
        View listItem = view;
        try {
            View v;
            while (!(v = (View) listItem.getParent()).equals(this)) {
                listItem = v;
            }
        } catch (ClassCastException e) {
            // We made it up to the window without find this list view
            return INVALID_POSITION;
        }

        // Search the children for the list item
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            if (getChildAt(i).equals(listItem)) {
                return mFirstPosition + i;
            }
        }

        // Child not found!
        return INVALID_POSITION;
    }
    /**
     * Get a view and have it show the data associated with the specified
     * position. This is called when we have already discovered that the view is
     * not available for reuse in the recycle bin. The only choices left are
     * converting an old view or making a new one.
     *
     * @param position The position to display
     * @param isScrap Array of at least 1 boolean, the first entry will become true if
     *                the returned view was taken from the scrap heap, false if otherwise.
     *
     * @return A view displaying the data associated with the specified position
     */
    View obtainView(int position, boolean[] isScrap) {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "obtainView");

        isScrap[0] = false;
        View scrapView;

        scrapView = mRecycler.getTransientStateView(position);
        if (scrapView == null) {
            scrapView = mRecycler.getScrapView(position);
        }

        View child;
        if (scrapView != null) {
            child = mAdapter.getView(position, scrapView, this);

            if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
                child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
            }

            if (child != scrapView) {
                mRecycler.addScrapView(scrapView, position);
                if (mCacheColorHint != 0) {
                    child.setDrawingCacheBackgroundColor(mCacheColorHint);
                }
            } else {
                isScrap[0] = true;

                // Clear any system-managed transient state so that we can
                // recycle this view and bind it to different data.
                if (child.isAccessibilityFocused()) {
                    child.clearAccessibilityFocus();
                }

                child.dispatchFinishTemporaryDetach();
            }
        } else {
            child = mAdapter.getView(position, null, this);

            if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
                child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
            }

            if (mCacheColorHint != 0) {
                child.setDrawingCacheBackgroundColor(mCacheColorHint);
            }
        }

        if (mAdapterHasStableIds) {
            final ViewGroup.LayoutParams vlp = child.getLayoutParams();
            LayoutParams lp;
            if (vlp == null) {
                lp = (LayoutParams) generateDefaultLayoutParams();
            } else if (!checkLayoutParams(vlp)) {
                lp = (LayoutParams) generateLayoutParams(vlp);
            } else {
                lp = (LayoutParams) vlp;
            }
            lp.itemId = mAdapter.getItemId(position);
            child.setLayoutParams(lp);
        }

        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
            if (mAccessibilityDelegate == null) {
                mAccessibilityDelegate = new ListItemAccessibilityDelegate();
            }
            if (child.getAccessibilityDelegate() == null) {
                child.setAccessibilityDelegate(mAccessibilityDelegate);
            }
        }

        Trace.traceEnd(Trace.TRACE_TAG_VIEW);

        return child;
    }

    class ListItemAccessibilityDelegate extends AccessibilityDelegate {
        @Override
        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
            // If the data changed the children are invalid since the data model changed.
            // Hence, we pretend they do not exist. After a layout the children will sync
            // with the model at which point we notify that the accessibility state changed,
            // so a service will be able to re-fetch the views.
            if (mDataChanged) {
                return null;
            }
            return super.createAccessibilityNodeInfo(host);
        }

        @Override
        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
            super.onInitializeAccessibilityNodeInfo(host, info);

            final int position = getPositionForView(host);
            onInitializeAccessibilityNodeInfoForItem(host, position, info);
        }

        @Override
        public boolean performAccessibilityAction(View host, int action, Bundle arguments) {
            if (super.performAccessibilityAction(host, action, arguments)) {
                return true;
            }

            final int position = getPositionForView(host);
            final ListAdapter adapter = getAdapter();

            if ((position == INVALID_POSITION) || (adapter == null)) {
                // Cannot perform actions on invalid items.
                return false;
            }

            if (!isEnabled() || !adapter.isEnabled(position)) {
                // Cannot perform actions on disabled items.
                return false;
            }

            final long id = getItemIdAtPosition(position);

            switch (action) {
                case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
                    if (getSelectedItemPosition() == position) {
                        setSelection(INVALID_POSITION);
                        return true;
                    }
                } return false;
                case AccessibilityNodeInfo.ACTION_SELECT: {
                    if (getSelectedItemPosition() != position) {
                        setSelection(position);
                        return true;
                    }
                } return false;
                case AccessibilityNodeInfo.ACTION_CLICK: {
                    if (isClickable()) {
                        return performItemClick(host, position, id);
                    }
                } return false;
                case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
                    if (isLongClickable()) {
                        return performLongPress(host, position, id);
                    }
                } return false;
            }

            return false;
        }
    }

    /**
     * Call the OnItemClickListener, if it is defined. Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @param view The view within the AdapterView that was clicked.
     * @param position The position of the view in the adapter.
     * @param id The row id of the item that was clicked.
     * @return True if there was an assigned OnItemClickListener that was
     *         called, false otherwise is returned.
     */
    public boolean performItemClick(View view, int position, long id) {
        if (mOnItemClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            if (view != null) {
                view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
            }
            mOnItemClickListener.onItemClick(this, view, position, id);
            return true;
        }

        return false;
    }
* 运用了一种设计模式:委托代理模式。借此可以学习或者巩固这一设计模式。
* obtainView() 方法可知,这是一个用于生成itemView的方法。
* ListItemAccessibilityDelegate类应该是一个委托类,对item的动作进行初始化,以及响应对应的操作。
* 从ListItemAccessibilityDelegate类代码可以知道,一个Item的View为什么对Click,LongClick,Select动作进行响应。
* 通过调用performItemClick()把事件调用到AdapterView.java里的performItemClick() 里面的监听器方法.

Adapter内部执行流程

    public void setAdapter(ListAdapter adapter) {
        ...
        if (mAdapter != null) {
            ...
            mItemCount = mAdapter.getCount();
            checkFocus();

            mDataSetObserver = new AdapterDataSetObserver();
            mAdapter.registerDataSetObserver(mDataSetObserver);

            mRecycler.setViewTypeCount(mAdapter.getViewTypeCount());
            ...
        } else {
            ...
        }

        requestLayout();
    }
    class AdapterDataSetObserver extends DataSetObserver {
        ...
        @Override
        public void onChanged() {
            mDataChanged = true;
            mOldItemCount = mItemCount;
            mItemCount = getAdapter().getCount();
            ...
            requestLayout();
        }

        @Override
        public void onInvalidated() {
            mDataChanged = true;
            ...
            requestLayout();
        }

        public void clearSavedState() {
            mInstanceState = null;
        }
    }
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        ...
        if (mItemCount > 0 && (widthMode == MeasureSpec.UNSPECIFIED ||
                heightMode == MeasureSpec.UNSPECIFIED)) {
            final View child = obtainView(0, mIsScrap);
            ...
        }
        ...
    }

    View obtainView(int position, boolean[] isScrap) {
        ...
        scrapView = mRecycler.getTransientStateView(position);
        if (scrapView == null) {
            scrapView = mRecycler.getScrapView(position);
        }

        View child;
        if (scrapView != null) {
            child = mAdapter.getView(position, scrapView, this);
            ...
        } else {
            child = mAdapter.getView(position, null, this);
            ...
        }

        if (mAdapterHasStableIds) {
            ...
            lp.itemId = mAdapter.getItemId(position);
            child.setLayoutParams(lp);
        }
        ...
        return child;
    }

    class RecycleBin {
        ...
        View getTransientStateView(int position) {
            if (mAdapter != null && mAdapterHasStableIds && mTransientStateViewsById != null) {
                long id = mAdapter.getItemId(position);
                ...
                return result;
            }
            ...
            return null;
        }

        View getScrapView(int position) {
            if (mViewTypeCount == 1) {
                return retrieveFromScrap(mCurrentScrap, position);
            } else {
                int whichScrap = mAdapter.getItemViewType(position);
                ...
            }
            return null;
        }
        ...
    }
上一篇下一篇

猜你喜欢

热点阅读