2012-05-04 291 views
3

我见过很多simillar问题,每个答案都是非常具体的问题,并没有直接的答案,或者我找到了教程,展示如何创建一个复选框,选中项目进行检查。 而且我无法理解如何从这些代码中完成它。如何更改ListView中选定项目的背景颜色?

我正在关注一个发现Here的教程,这很像我的代码看起来只有不同的名字。

我想要有一个多选择ListView,当一个项目选择了背景颜色被改变来标记我选择的项目。

也许我可以使用自定义选择器来实现这一点? 我明白常用的方法是保存所选位置并在getView函数中执行某些操作。 我看到有人在创建ViewHolder,但我并不真正了解它与什么有关。 有人可以帮我吗?

预先感谢, 埃里克

回答

13

嗯,我终于解决了这个问题,希望这可以帮助别人:

我所做的就是创建一个ArrayList<Integer>存储所选项目的所有位置,以及切换背景颜色点击次数。

以我适配器我定义:

public ArrayList<Integer> selectedIds = new ArrayList<Integer>(); 

以下方法:

public void toggleSelected(Integer position) 
{ 
    if(selectedIds.contains(position)) 
    { 
     selectedIds.remove(position); 


    } 
    else 
    { 
     selectedIds.add(position); 
    } 
} 

其中就将此\从该ArrayList

移除项以我getView方法:

  if (selectedIds.contains(position)) { 
      convertView.setSelected(true); 
      convertView.setPressed(true); 
      convertView.setBackgroundColor(Color.parseColor("#FF9912")); 
     } 
     else 
     { 
      convertView.setSelected(false); 
      convertView.setPressed(false); 
      convertView.setBackgroundColor(Color.parseColor("#000000")); 
     } 

这将检查该位置是否存储在ArrayList中。如果是,则将其绘制为选定的。如果不是,则相反。

所有剩下的只有OnItemClick听者,我说:

((YourAdapter)list.getAdapter()).toggleSelected(new Integer(position)); 

当YourAdapter是你的ListView

希望的适配器,这可以帮助任何人,因为它是一个通用的答案:)

+0

我面临着同样的问题,但是在您的解决方案中,我无法理解什么是“列表”? – Rohit

+0

这就是我在OnItemClick事件中命名的方式 –

+0

完美的答案,非常感谢! – Claud

0

您还可以将以下选择器设置为背景以列出项目布局:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_selected="true" android:drawable="@color/android:transparent" /> 
    <item android:drawable="@drawable/listitem_normal" /> 
</selector> 

来源:ListView item background via custom selector

0

有一个普通的XML解决方案。下面的语法是WRT API 15 我用下面的列表项的模板:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@drawable/item_selection"> 
    <ImageView /> 
    <.. /> 
</LinearLayout> 

它指向在res文件item_selection.xml /提拉 - 华电国际(Android Studio中0.8。14):

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

    <item android:drawable="@android:color/holo_blue_dark" android:state_selected="true" /> 
</selector> 
相关问题