滚动时,带有selector属性的listview不会正确更改

时间:2013-07-23 08:47:45

标签: android listview android-listview android-selector

我正在使用selector属性处理listview,当用户选择索引位置应突出显示的索引位置,直到我选择listview的下一个索引位置时,selector属性与此一起工作但是当我滚动列表视图选择器时它在顶部移动时不起作用。请帮帮我这个

<ListView
        android:id="@+id/lvMenuItem"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:listSelector="@color/selected_color"
        android:dividerHeight="3dp" >
    </ListView>

lvMenu.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                //view.setSelected(true);
                Log.d("das","dasdas");
                if(lastSelected != null) {
                    lastSelected.setBackgroundColor(Color.TRANSPARENT);//(dr/*id of your unselected drawable*/);
                }
                lastSelected = (ViewGroup)view;
                lastSelected.setBackgroundResource(R.color.selected_color/*id of your selected drawable*/);
               // selectedRow=position; 
                String photo =datasource.getImagePathFromSubMenuId(SubMnuIdlst.get(position));
                Bitmap theImage= BitmapFactory.decodeFile(ofFilePath+"/"+photo);
                Bitmap bitmapScaled = Bitmap.createScaledBitmap(theImage, 300,250, true);
                drawable = new BitmapDrawable(bitmapScaled);
                imgMainItem.setBackgroundDrawable(drawable); 
                Imagename=ServerPath+"images/"+photo;
                String Desc=datasource.getSubMenuDescriptionFromSubMenuId(SubMenuid12);
                tvDesc.setText(Desc);
                selectionPos=position;
                selectedimgpath=photo;
                menuAdapter.notifyDataSetChanged();
                Log.d("SelPos",""+selectionPos);
            }
        }); 

Left side of image is the listview

1 个答案:

答案 0 :(得分:2)

您应该跟踪lastSelected位置,并在listView的onItemClickListener中取消选择lastSelected位置并选择当前位置..这样的事情

ListView myListView = (ListView)findViewById(/* id of listView */);
ViewGroup lastSelected = null;
myListView.setOnItemClickListener(new onItemClickListener(
@Override
onItemClick(AdapterView arg0, View childView, int pos) {
    if(lastSelected != null) {
        lastSelected.setBackgroundDrawable(/*id of your unselected drawable*/);
    }
    lastSelected = (ViewGroup)childView;
    lastSelected.setBackgroundDrawable(/*id of your selected drawable*/);
    }
 ));