Android开发:通过代码动态改变ListView选中的item背景色

int deviceIndex=-9999;//记录选中的item,-9999表示无选中记录
ListView lv_InstrumentItem=findViewById(R.id.lv_InstrumentItem_CommunicationSettingsActivity);
lv_InstrumentItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                if (deviceIndex == -9999) {//初始选中,该item背景色设置为黄色
                    deviceIndex = position;
                    view.setBackgroundColor(Color.YELLOW);
                } else if (deviceIndex == position) {//选中后的item,再点击后恢复原背景色(白色),即取消选中
                    deviceIndex = -9999;
                    view.setBackgroundColor(Color.WHITE);
                } else {//改变选中的item时,原选中的item背景色恢复为白色,新选中的背景色设置为黄色
                    lv_InstrumentItem.getChildAt(deviceIndex).setBackgroundColor(Color.WHITE);
                    view.setBackgroundColor(Color.YELLOW);
                    deviceIndex = position;
                }                
            }
        });

你可能感兴趣的:(Android,JAVA,Controls)