`

ListView点击背景色更换(数据量大,显示小时会多选)

阅读更多

创建一个大小长度固定的dialog,当动态显示数据时,如果显示的数据太多,会出现同时选中多行的情况。

环境:自定义一个类,dialog中使用listview,不做分页处理,一次性全部显示出来。

点击事件代码如下:

GuestInfoListAdapter guestinfoAdapter = new GuestInfoListAdapter(guestInfoList);
        guestInfoListInfo.setAdapter(guestinfoAdapter);
        guestInfoListInfo.setOnItemClickListener(new OnItemClickListener() {
           
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                selectHaccnt = guestInfoList.get(arg2).getNo();
                arg1.setBackgroundColor(Color.BLUE);
               
                if(oldView != null && old_position != arg2){
                    oldView.setBackgroundColor(Color.TRANSPARENT);   
                }
                old_position = arg2;
                oldView = arg1;
            }
        });

 

注:old_position(Integer)和oldview(View)是全局变量

产用上面的方式来实现点击哪一行,哪一行变成蓝色。 但是如果是数据量比较大,滑动查看有两页以上。

那么点击任意一行,都会同时选中多行。

原因是:采用上面的方式,当点击了该行后,没有刷新整个adapter,导致后面的虚页也同时显示为选中状态。

解决方法:通过adapter来控制背景的变化,把点选中的行号传递给adapter,adapter的getView方法中做背景变更操作。

Dialog中:

final GuestInfoListAdapter guestinfoAdapter = new GuestInfoListAdapter(guestInfoList);
        guestInfoListInfo.setAdapter(guestinfoAdapter);
        guestInfoListInfo.setOnItemClickListener(new OnItemClickListener() {
           
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                selectHaccnt = guestInfoList.get(arg2).getNo();
                guestinfoAdapter.setSelectedIndex(arg2);
                guestinfoAdapter.notifyDataSetInvalidated();
            }
        });

 

Adapter中:

先添加一个私有变量int型,书写其set方法。

private int selectedIndex = -1;
   
    public GuestInfoListAdapter(List<Guest> guestInfoList){
        this.guestInfoList = guestInfoList;
    }

    public void setSelectedIndex(int selectedIndex) {
        this.selectedIndex = selectedIndex;
    }

 

getView方法中,做背景变更:

if (position == selectedIndex){
            guestInfoListView.setBackgroundColor(Color.BLUE);
        }else
        {
            guestInfoListView.setBackgroundColor(Color.TRANSPARENT);
        }

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics