【问题标题】:How to set background color of list item which is clicked in android?如何设置在android中单击的列表项的背景颜色?
【发布时间】:2013-06-06 19:30:56
【问题描述】:

我创建了一个列表视图。当我单击列表中的任何项目时,我想为其设置背景。当我单击以前删除的其他项目背景并设置为其他项目时。我该如何实现这一点。我尝试了几种方式。我尝试过使用选择器和其他方式。 代码sn-p如下:_

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

<item
    android:state_pressed="true"
    android:drawable="@color/selectedItem" />
<item
    android:state_focused="true"
    android:drawable="@color/GREEN" />
<item
    android:drawable="@color/BLACK" />

Activity的代码

bookListView = (ListView) findViewById(R.id.list_books);
/*  selectedView = null;
    bookListView.invalidate();*/
    bookListView.setSelector( R.drawable.list_selector);

【问题讨论】:

  • 这个 ListView 使用什么样的适配器?
  • 我正在使用 arrayAdapter.
  • 对项目应用点击事件,然后改变背景布局的颜色。
  • yes, i am trying this way also but how can i remove color when selects oteher.请给一些代码sn-p。
  • 我会使用自定义适配器,但可能有一种方法可以使用 onItemClickListener

标签: android listview background selection


【解决方案1】:

你可以这样做:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                // We store the current position of the selected item
                mSelectedItem = position;
                // We refresh a custom adapter
                mAdapter.notifyDataSetChanged();
            }
        }
    };

在自定义适配器中覆盖 getView 方法:

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final View view = View.inflate(mContext, R.layout.item_list, null);

            if (position == mSelectedItem) {
                //Set active style
            }

            return view;
        }

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2013-11-04
    • 2011-11-09
    • 1970-01-01
    相关资源
    最近更新 更多