如何在android中的适配器列表视图中更改背景颜色?

时间:2014-07-06 04:58:50

标签: android listview android-listview listadapter

在适配器列表视图中第一次单击行的列表视图,它不工作但第二次它正在工作,行背景颜色被更改。请建议我如何正常工作。

productList.setOnItemClickListener(new OnItemClickListener() {

        //mOnDoubleTapListener = listener;

        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

            Log.d("Row", "Row:= "+row);
            Log.d("View", "View:= "+view);

            if(row != null) {
                row.setBackgroundColor(Color.WHITE);
            }


            view.setBackgroundColor(Color.CYAN);

            row = view;
            }});

1 个答案:

答案 0 :(得分:3)

使用这种方式: - 此代码将有助于您更改所选列表视图项目的颜色

只需在您的活动中调用一个名为SELECTED_POSITION = -1的变量;

当您点击ListView中的任何项目时,您将通过此代码获得单击的位置

productList.setOnItemClickListener(new OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

            SELECTED_POSITION =position;
        }
     });

然后实现自定义适配器类,其中@override方法称为getView(...)

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
    ViewHolder holder = null;
    if (convertView == null) {
        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.row_adptr, null);
        holder = new ViewHolder();
        holder.text = (TextView) convertView
                .findViewById(R.id.adapterText1);
        holder.chkbox = (CheckBox) convertView
                .findViewById(R.id.checkBox1);
        holder.imageview = (ImageView) convertView
                .findViewById(R.id.imageView1);
        convertView.setTag(holder);          

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

       // this is the code when selected item stay at one position 
       if(position ==SELECTED_POSITION)
       {
            // set your selected Item Color
             convertView.setBackgroundColor(Color.WHITE);
       }
        else
       {   // set your unselected Item Color
               convertView.setBackgroundColor(Color.CYAN);
       } 

     ....Extra code of set value...
 }