自定义Adapter IndexOutOfBoundsException

在Android开发过程中,有个基本的技能就是自定义adapter,给列表填充数据。如果列表里有两种或者两种以上的不同的item,那么我们可以用adapter.getItemViewType(position)拿到该item的视图类型,再根据这个类型在adapter.getView(position, convertView, parent)方法里创建不同的view添加进去。比如简单的聊天记录,大概就是这个样子:

Paste_Image.png

我是这么做的。

定义一个Model类ChatRecord.java用来存储每条消息记录

public class ChatRecord {
    private String content;//消息内容
    private int type; //类型 0代表你的发言,1代表别人发言

    public String getContent() {
        return content;
    }

    public ChatRecord setContent(String content) {
        this.content = content;
        return this;
    }

    public int getType() {
        return type;
    }

    public ChatRecord setType(int type) {
        this.type = type;
        return this;
    }
}

自定义一个Adapter,给listView用来添加数据

public class ChatRecordAdapter extends BaseAdapter {
    public static final int TYPE_YOUR = 0; //你的发言
    public static final int TYPE_OTHERS = 1; //其他人的发言

    private Context mContext;
    private ArrayList<ChatRecord> mData;

    public ChatRecordAdapter(Context mContext, ArrayList<ChatRecord> mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @Override
    public int getViewTypeCount() {
        return mData.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mData.get(position).getType();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int viewType = getItemViewType(position);
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = createView(viewType);

            viewHolder = new ViewHolder();
            viewHolder.ivHeadPortrait = (ImageView) convertView.findViewById(R.id.ivHeadPortrait);
            viewHolder.tvChatContent = (TextView) convertView.findViewById(R.id.tvChatContent);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.ivHeadPortrait.setImageResource(getImageResource(viewType));
        viewHolder.tvChatContent.setText(mData.get(position).getContent());
        return convertView;
    }

    private View createView(int type) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        switch(type) {
            case TYPE_YOUR:
                return inflater.inflate(R.layout.chat_record_item_yours, null);
            case TYPE_OTHERS:
                return inflater.inflate(R.layout.chat_record_item_others, null);
        }
        return null;
    }

    private int getImageResource(int type) {
        switch(type) {
            case TYPE_YOUR:
                return R.mipmap.ic_launcher;
            case TYPE_OTHERS:
                return R.color.colorPrimaryDark;
        }
        return R.color.colorAccent;
    }

    class ViewHolder {
        public ImageView ivHeadPortrait;
        public TextView tvChatContent;
    }
}

自定义adapter涉及到的资源文件
chat_record_item_yours.xml

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

    <ImageView
        android:id="@+id/ivHeadPortrait"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@mipmap/ic_launcher" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/ivHeadPortrait">

        <TextView
            android:id="@+id/tvChatContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" />
    </RelativeLayout>

</RelativeLayout>

chat_record_item_others.xml

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

    <ImageView
        android:id="@+id/ivHeadPortrait"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@mipmap/ic_launcher"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"/>

    <TextView
        android:id="@+id/tvChatContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/ivHeadPortrait"/>

</RelativeLayout>

编写主界面代码

并且在聊天记录底部加一个View作为广告展示(没有点击跳转,只作展示),每条聊天记录可以点击,点击时Toast提示是谁的发言。代码大概是这样子:

public class MainActivity extends Activity {
    private ListView lvBank;
    private ChatRecordAdapter mAdapter;

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

        initView();
        initData();
    }

    private void initView() {
        lvBank = (ListView) findViewById(R.id.lvBank);
        lvBank.addFooterView(getFooterView());//这句代码应该在setAdapter()之前调用
    }

    private void initData() {
        mAdapter = new ChatRecordAdapter(this, getData());
        lvBank.setAdapter(mAdapter);
        lvBank.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int viewType = mAdapter.getItemViewType(position);
                String toastMsg = viewType == ChatRecordAdapter.TYPE_YOUR ? "your speck" : "others' speck";
                Toast.makeText(MainActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 创建列表底部View
     * @return
     */
    private View getFooterView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        return inflater.inflate(R.layout.bottom_advertisement, null);
    }

    /**
     * 用来生成简单的聊天记录
     * @return
     */
    private ArrayList<ChatRecord> getData() { 
        ArrayList<ChatRecord> data = new ArrayList<>();
        ChatRecord record;
        for (int i = 0; i < 20; i++) {
            record = new ChatRecord();
            if (i % 2 == 0) {
                record.setType(ChatRecordAdapter.TYPE_YOUR).setContent("honey, what r u doing?  " + i);
            } else {
                record.setType(ChatRecordAdapter.TYPE_OTHERS).setContent("- - - - -  " + i);
            }
            data.add(record);
        }
        return data;
    }

}

涉及到的资源文件
bottom_advertisement.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="this is bottom advertisement"
        android:gravity="center"/>
</LinearLayout>

运行代码,查看结果

运行结果如文章开始那张图,但是有个问题,也是我写这个的目的,那就是:
当点击到footerView的时候,程序崩溃了!!!

可以看到,报错的原因是IndexOutOfBoundsException ~
断点调试可以看到,是进入到了ListView的onItemClick事件当中~
我们根本没有设置footerView的点击事件啊,为什么会有呢?我们看一下跟footerView相关的代码

lvBank.addFooterView(getFooterView());

点进入看一下addFooterView到底做了什么:

/**
     * Add a fixed view to appear at the bottom of the list. If addFooterView is
     * called more than once, the views will appear in the order they were
     * added. Views added using this call can take focus if they want.
     * <p>
     * Note: When first introduced, this method could only be called before
     * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
     * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
     * called at any time. If the ListView's adapter does not extend
     * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
     * instance of {@link WrapperListAdapter}.
     *
     * @param v The view to add.
     */
    public void addFooterView(View v) {
        addFooterView(v, null, true);
    }

这里看到,是调用了其三个参数的重载方法,再进入看看:

/**
     * Add a fixed view to appear at the bottom of the list. If addFooterView is
     * called more than once, the views will appear in the order they were
     * added. Views added using this call can take focus if they want.
     * <p>
     * Note: When first introduced, this method could only be called before
     * setting the adapter with {@link #setAdapter(ListAdapter)}. Starting with
     * {@link android.os.Build.VERSION_CODES#KITKAT}, this method may be
     * called at any time. If the ListView's adapter does not extend
     * {@link HeaderViewListAdapter}, it will be wrapped with a supporting
     * instance of {@link WrapperListAdapter}.
     *
     * @param v The view to add.
     * @param data Data to associate with this view
     * @param isSelectable true if the footer view can be selected
     */
    public void addFooterView(View v, Object data, boolean isSelectable) {
        final FixedViewInfo info = new FixedViewInfo();
        info.view = v;
        info.data = data;
        info.isSelectable = isSelectable;
        mFooterViewInfos.add(info);
        mAreAllItemsSelectable &= isSelectable;

        // Wrap the adapter if it wasn't already wrapped.
        if (mAdapter != null) {
            if (!(mAdapter instanceof HeaderViewListAdapter)) {
                mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, mAdapter);
            }

            // In the case of re-adding a footer view, or adding one later on,
            // we need to notify the observer.
            if (mDataSetObserver != null) {
                mDataSetObserver.onChanged();
            }
        }
    }

仔细看一下这里的注释@param isSelectable true if the footer view can be selected
原来问题出在这里~~~

所以,ListView添加列表头或者列表尾时,一定注意调用哪个方法,如果不期望其可点击,则需要调用三参数重载方法public void addFooterView(View v, Object data, boolean isSelectable),并且isSelectablefalse,不然会出现IndexOutOfBoundsException

写在最后

其实写这篇文章就只是为了说明在添加列表头或列表尾时要注意调用的方法,跟自定义adapter没什么太大关系,花那么多时间写自定义adapter只得算是练练手。
以上全部基于自己的理解 ,如有问题,欢迎批评指正~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,653评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,321评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,833评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,472评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,306评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,274评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,658评论 3 385
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,335评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,638评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,697评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,454评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,311评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,699评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,986评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,254评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,647评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,847评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,117评论 25 707
  • 注意:此文译自JaCoCo官方介绍文档,如有出错之处,烦请指出,不胜感激。点击此处,查看原文 覆盖率计数器 JaC...
    yoyo_zyx阅读 1,720评论 0 3
  • 2.4 可变数据 来源:2.4 Mutable Data 译者:飞龙 协议:CC BY-NC-SA 4.0 我...
    布客飞龙阅读 593评论 1 37
  • 啥是共享经济?本人认为将社会闲置资源合理利用,使供需双方成本和收益达到平衡的一种新型产业经济。 共享经济平...
    诚品阅读 312评论 0 0
  • 预计明天会有一个突破,这几天说忙也忙也懒散也懒散,明天有一波突破,破20吧。
    杨奶茶阅读 177评论 0 0