【问题标题】:Android: Change color of 1 listview entry applies on every 9thAndroid:每 9 次更改 1 个列表视图条目的颜色
【发布时间】:2018-06-13 16:57:58
【问题描述】:

我正在编写一个小的 android 应用程序。 我有一个列表视图的问题。 单击条目时,应将数据结构的状态标记为选中或未选中。在数据结构中一切都很好,但是应该通过更改条目的背景颜色来可视化选择。 到目前为止一切都很好,但是在单击正确的元素后会更改其颜色,而且 每 9 个 元素(单击条目 0 -> 更改颜色,还有条目 8、条目 16 等等)在listview 但我不知道为什么。

问题:为什么不只是点击的条目改变了颜色?

这是我的 getView 代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItem = convertView;
    if (listItem == null)
        listItem = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);

    final User currentUser = userList.get(position);

    TextView username = listItem.findViewById(R.id.lv_username);
    String state = "disabled";
    if(currentUser.getSelected()) state = "enabled";
    username.setText(currentUser.getUsername() + " - " + state);
    listItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            currentUser.setSelected(!currentUser.getSelected());
            if (currentUser.getSelected()) {
                Log.d("onClick in Adapter", "selected");
                v.setBackgroundColor(Color.WHITE);
            }
            else {
                Log.d("onClick in Adapter", "not selected");
                v.setBackgroundColor(Color.TRANSPARENT);
            }
            notifyDataSetChanged();
        }
    });
    return listItem;
}

【问题讨论】:

    标签: android listview adapter


    【解决方案1】:

    这就是回收视图的工作方式,由于正在使用以前不可见的视图,因此会保留所有状态,因此在重用时它已经着色(注意,如果单击它不会变得透明,但是单击两次会导致数据结构完好)。

    解决方案是始终将状态重新应用于即将变为可见的视图。

    if (listItem == null)
        listItem = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);
    listItem.setBackgroundColor(currentUser.getSelected() ? Color.WHITE : Color.TRANSPARENT);
    

    【讨论】:

      【解决方案2】:

      你试过了吗,在 getview 中检查位置是否等于第 9 行,然后更改该行的背景颜色。

      if (position==9){
                  convertView.setTextColor(Color.RED);
      }
      

      【讨论】:

      • 我听不懂这个问题.. 但是看了你的回答后,我又不明白了!
      • 他想改变listview中第9行的颜色。
      • 我只是让他大致了解如何实现它。通过获得位置并执行所需的操作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      相关资源
      最近更新 更多