【问题标题】:ListView items are not marked when pressed按下时未标记 ListView 项目
【发布时间】:2011-12-10 01:16:03
【问题描述】:

我正在实现一个 Android 活动。 我在我的应用程序布局中使用 ListView,并在继承的 SimpleAdapter getView 中通过 setBackgroundResource 设置视图颜色。

public class SpecialAdapter extends SimpleAdapter {

    public SpecialAdapter(Context context, List<HashMap<String, String>> items, int resource, String[] from, int[] to) {
        super(context, items, resource, from, to);
    }

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

       View view = super.getView(position, convertView, parent);

       if (mSensorsStatus[position].equals(mSensorStatus[SENSOR_STATUS_ALERT])) {
          view.setBackgroundResource(R.color.red);
       }
       else if (mSensorsStatus[position].equals(mSensorStatus[SENSOR_STATUS_ARMED])) {
          view.setBackgroundResource(R.color.light_grey);
       }

       return view;
    }
}

我的问题是,当我单击其中一个项目时,它没有像通常那样以黄色/橙色着色(删除 setBackgroundResource 时它工作正常)

更多信息: 我尝试通过 mListView.getChildAt(index).setBackgroundResource(R.color.red) 而不是设置背景颜色 getView 实现,结果是一样的。

感谢您的帮助

【问题讨论】:

  • 呃,你用的是什么语言?什么 GUI 工具包?
  • 抱歉,忘了说这是一个 Android 活动...

标签: android listview


【解决方案1】:

那是因为您调用了setBackgroundResource() 并将背景设置为一种颜色。如果您希望列表选择起作用,请不要调用setBackgroundResource(),或者将后台资源设置为具有选择器和所有其他必要状态的合适StateListDrawable

【讨论】:

  • 问题是我需要对item至少有5种不同的可能颜色(我发送的代码是部分的,getView中有更多的条件和颜色)。那么如何在不使用 setBackgroundResource 的情况下用想要的颜色为每个项目着色呢? StateListDrawable 有这种灵活性吗?
  • @Zvi:您可能需要五个资源,每种颜色一个,每个StateListDrawable。我强烈建议您重新考虑以这种方式更改背景颜色的策略,因为您的 UI 模型在 Android 上运行不佳,尤其是在 Android 3.0 上。更改其他内容的颜色(例如,一侧下方的彩色条)。
  • 我正在尝试将StateListDrawableLevelListDrawable 一起使用,这样我就可以支持不止一种颜色。我会尽快更新结果
  • 我可以将StateListDrawable 与颜色一起使用而不是与 png 文件一起使用吗?
【解决方案2】:

LayerList drawable 可以匹配您想要的行为,如下所述: ListView item with list_selector_background as LayerList drawable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多