Search code examples
androidlistviewandroid-listviewlistadapter

How to change background colour in adapter list view in android?


In adapter listview first time click on listview of row, it is not working but second time it is working, the row background color is changed. Please suggest me how is working fine.

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;
            }});

Solution

  • Use this way:-- This code will help to u for change the color of selected Item of listview

    Just take one variable Called SELECTED_POSITION=-1 in your activity;

    When u clicked any item in ListView the position which is clicked that u will get by this code

    productList.setOnItemClickListener(new OnItemClickListener() {
    
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
    
                SELECTED_POSITION =position;
            }
         });
    

    then implement Custom Adapter Class in which @override method is there is called 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...
     }