2014-03-29 97 views
0

我有一个使用自定义适配器的列表视图。在列表视图中唯一的项目是一个TextView(现在)。当我点击TextView时,背景颜色应该变成蓝色,当我再次点击它时,背景颜色应该变成默认颜色(浅灰色)。我正在尝试使用ViewHolder模式来实现这一点。ViewHolder模式 - ListView - 项目的背景颜色设置不正确

现在的问题是,当我点击列表中的第一个项目时,一些随机项目的背景颜色会变成蓝色。

CustomAdapter类:

public class ResultsAdapter extends BaseAdapter { 

    ViewHolder holder; 

    @Override 
    public int getCount() { 
     return dummyText.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     return position; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     if (convertView == null) { 
      convertView = getActivity().getLayoutInflater().inflate(
        R.layout.item_mtf_results, parent, false); 

      holder = new ViewHolder(); 
      holder.txtViewResults = (TextView) convertView 
        .findViewById(R.id.textview_item_mtf_results); 

      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     holder.txtViewResults.setText(dummyText[position]); 

     holder.txtViewResults.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       Log.d(Const.DEBUG, "in onClick Method"); 
       Log.d(Const.DEBUG, "Is checked ? = " + holder.isChecked); 

       String result = holder.txtViewResults.getText().toString(); 
       listener.onResultClick(result); 

       if (holder.isChecked) { 

        Log.d(Const.DEBUG, "isChecked = true"); 

        holder.txtViewResults.setBackgroundColor(getResources() 
          .getColor(R.color.light_grey)); 
        holder.txtViewResults.setTextColor(getResources() 
          .getColor(R.color.black)); 
        holder.isChecked = false; 

        Log.d(Const.DEBUG, 
          "Holder is set to false.. checked ? = " 
            + holder.isChecked); 

       } else { 

        Log.d(Const.DEBUG, "isChecked = false"); 

        holder.txtViewResults.setBackgroundColor(getResources() 
          .getColor(R.color.blue)); 
        holder.txtViewResults.setTextColor(getResources() 
          .getColor(R.color.white)); 
        holder.isChecked = true; 

        Log.d(Const.DEBUG, 
          "Holder is set to true.. checked ? = " 
            + holder.isChecked); 
       } 

      } 
     }); 

     return convertView; 
    } 

} 

ViewHolder类:

public static class ViewHolder { 
    TextView txtViewResults; 
    boolean isChecked = false; 
} 

让我知道如果你需要任何其他代码...

+0

您为什么需要在支架中检查?请参阅是否可以将布尔值作为标记设置为textview。 – km86

回答

0

尝试添加clickListenr文本视图内converview==null块。每次滚动列表视图时都会设置Listners。