0

我有一个 ListView 并且可以选择一个元素(单选)。

选择某个项目时,如何为 ListView 的所有元素(可能至少是可见的)设置背景颜色?

adapter = new ArrayAdapter<Orderline>(activity, simple_list_item_single_choice, orderlines) {
    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        ...
        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                convertView.setBackgroundColor(BLACK);
                // so here currently selected element is set to BLACK, but also other elements have to be set to WHITE
            }
        });
        return convertView;
    }
}
4

4 回答 4

1

我没有太多代码给你,因为我现在不在我的工作站,但我想你可以通过你的 onItemClick 将所选项目的背景设置为黑色,就像你已经建议的那样。凉爽的。

要在选择特定视图时更改其他(未选择)视图的颜色,我猜您可以调用适配器的 getCount() 并遍历该列表,调用 ListView 的 getChildAt(i)。这将返回一个视图,您可以在其上调用 setBackgroundColor(Color)。希望这可以帮助

于 2013-07-15T16:53:12.897 回答
0

你可以做

parent.setBackgroundColor(BLACK);
this.notifyDataSetChanged();

设置您的列表视图背景。

于 2013-07-15T16:44:03.910 回答
0

我会使用 Drawable 选择器。

检查此链接以获得一个很好的示例: http: //www.charlesharley.com/2012/programming/custom-drawable-states-in-android/

基本上,您创建 XML 可绘制对象,其中包含映射(系统自动使用)到您希望在发生某些单击事件时显示的内容。

您可以将背景可绘制对象分配给任何视图,因此您可以在适配器的 XML 或 Java 代码中执行此操作。在你的情况下可能是这样的:

convertView.setBackgroundDrawable(R.drawable.MySelector);
于 2013-07-15T17:08:25.963 回答
0

parent.setBackgroundColor(while_color); v.setBackgroundColor(black_color)

于 2013-07-15T17:12:42.967 回答