android listView 怎么指定项的背景设置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android listView 怎么指定项的背景设置相关的知识,希望对你有一定的参考价值。

想设置ListView 某一项的背景颜色,求高手指导。先说明不是点击那项,而是指定的第n项,例如,我想只设置第20项的背景图片。本以为下面两行代码搞定,但是什么反应都没有。
listView.setSelection(i);
listView.setSelector(getResources().getDrawable(R.drawable.background));
但是点击某项后调用 listView.setSelector(getResources().getDrawable(R.drawable.background));就行了。
问题是我要的不是设置点击那项的背景。而是我指定的项

    android listview指定项设定背景步骤如下:

    监听列表项监听事件,取得被点击的view,设置为:view.setSelector("true");

2.在适配器中,用if-else语句,判断选择的列表项设置背景,没有选中的则默认背景,代码如下:


try   
    if (selectItem == position)   
        messagetitle.setTextColor(android.graphics.Color.BLACK);  
        messagetime.setTextColor(android.graphics.Color.BLACK);  
        viewHolder.messagetitle.setText(maps.get(position)  
                .get("messagetitle").toString());  
        viewHolder.messagetime.setText(maps.get(position)  
                .get("messagetime").toString());  
        convertView.findViewById(R.id.expandable1)  
                .setBackgroundColor(android.graphics.Color.WHITE);  
        convertView.findViewById(R.id.expandable1)  
                .setBackgroundResource(R.drawable.menu_shapeclick);  
     else   
        messagetitle.setTextColor(android.graphics.Color.WHITE);  
        messagetime.setTextColor(android.graphics.Color.WHITE);  
        viewHolder.messagetitle.setText(maps.get(position)  
                .get("messagetitle").toString());  
        viewHolder.messagetime.setText(maps.get(position)  
                .get("messagetime").toString());  
        convertView.findViewById(R.id.expandable1)  
                .setBackgroundResource(  
                        R.drawable.menu_shapeunonclick);  
      
 catch (Exception ex)   
    ex.printStackTrace();  
  
return convertView;
参考技术A 在设置ListView的adapter的时候,在getView方法中可以设置,根据传来的position参数知道是第几项,就可以设置了
搞个数组,再搞个求余的函数就可以循环设置了
参考技术B 你可以在适配器的getview里面,通过position判断,然后加载不同的小布局。小布局里面设置背景色。 参考技术C 1、可以在listview中的adpater里面改写getview方法;
2、在getview中会有int position,可以根据这个拿到指定项,然后做处理。
参考技术D 这个问题可以通过刷新适配器实现,首先自定义适配器类,在适配器类中定义一个mySelection属性,在定义一个setMySelection(int index)mySelection = index;notifyDataSetChanged();方法,在getView方法中判断当前返回的view的索引是否和mySelection相等,相等的话设置专门准备的背景即可。使用的方法是:在用到该适配器的地方调用一下setMySelection方法,不要忘了传递你要改变背景选项的索引值。
注意setMySelection方法中的notifyDataSetChanged();很重要 希望对你有帮助。

以上是关于android listView 怎么指定项的背景设置的主要内容,如果未能解决你的问题,请参考以下文章

Android如何在每个listview列表项上添加图标并更改文本颜色、背景颜色

从自定义列表 Xamarin 中设置所选列表视图项的背景颜色

Android listview 项目使用数组适配器在图像上显示文本

android listview每一个item点击换个背景图或者背景色。要怎么做?求教

listview Android每一项的选项

Android ListView:获取可见项的数据索引