如何使用onItemSelectedListener更改视图的颜色

时间:2014-11-22 04:42:34

标签: android android-layout

我似乎无法锻炼如何使onItemSelectedListender接口工作。我想更改所选项目的颜色,然后在取消选择后将其更改回来。我已经完成了一些阅读,并且我已经设法用onItemSelectedListener做了类似的事情。

我的代码是

libraryGrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            //I want to change the color of the view that was just selected
            view.setBackgroundColor(Color.GRAY);
            adapterView.getSelectedView().setBackgroundColor(Color.YELLOW);

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            //How do I access the view that was just unselected to change it's color?
            adapterView.setBackgroundColor(Color.BLACK);
        }
    });

1 个答案:

答案 0 :(得分:1)

您可以跟踪所选项目并从getView方法更改该项目的背景。

以这种方式试试..

libraryGrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

             mSelectedItem = position;
                mAdapter.notifyDataSetChanged();


        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

并在yout getView方法中设置所选项目的背景颜色。

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

        if (position == mSelectedItem) {
            //set Selected color as background on view
        }
        else{
           //set unSelected color as background on View
        }

        return view;
    }