1

i m new in list view , i want to item click on listview it change background color , it change but i after scroll it changes other item background view also. i cant find out where i am wrong ?

code snippet : ListColorChange.java

package com.example.spinnerfilter;



 public class ListColorChange extends Activity {

 private ListView phproductinfo;
 ArrayList<ProductInfo> arrayListProf;
ChangeColorAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.demo);

    init();
}

int mselected = -1;

public void init() {

    phproductinfo = (ListView) findViewById(R.id.phlist);

    arraylistInit();

    adapter = new ChangeColorAdapter(ListColorChange.this, arrayListProf);

    phproductinfo.setAdapter(adapter);

    phproductinfo.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            mselected = position;
            ProductInfo info = arrayListProf.get(position);

            info.setOngoing(true);

            adapter.notifyDataSetChanged();

        }
    });

}

private void arraylistInit() {

    String name[] = { "India", "Austrai", "Xyxz", "Pask", "New", "India",
            "Austrai", "Xyxz", "Pask", "New", "India", "Austrai", "Xyxz",
            "Pask", "New", "India", "Austrai", "Xyxz", "Pask", "New",
            "India", "India", "Austrai", "Xyxz", "Pask", "New", "India",
            "India", "Austrai", "Xyxz", "Pask", "New", "India", "India",
            "Austrai", "Xyxz", "Pask", "New", "India" };
    arrayListProf = new ArrayList<ProductInfo>();
    for (int i = 0; i < name.length; i++) {
        ProductInfo info = new ProductInfo();

        info.setDisplay_name(name[i]);
        info.setOngoing(false);

        arrayListProf.add(info);
    }

}

   public class ChangeColorAdapter extends BaseAdapter

   {

    public ChangeColorAdapter(ListColorChange listColorChange,
            ArrayList<ProductInfo> arrayListProf) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return arrayListProf.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return arrayListProf.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        // TODO Auto-generated method stub
        ViewHolder vh;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater
                    .from(ListColorChange.this);
            convertView = inflater.inflate(R.layout.productlist, null);
            TextView product_name = (TextView) convertView
                    .findViewById(R.id.prod_name);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        if (arrayListProf != null && arrayListProf.size() > 0) {
            ProductInfo pi = arrayListProf.get(position);
            if (pi.getDisplay_name() != null) {
                vh.product_name.setText(pi.getDisplay_name());
            }
            if (arrayListProf.get(position).isOngoing() && mselected ==                         position) {
                    convertView.setBackgroundColor(Color.parseColor("#ff0000"));
            }
        }

        return convertView;
    }

    class ViewHolder {
        TextView product_name;
        TextView qty;
        TextView unit;
        int position;

        boolean ispu = false;

        public ViewHolder(View view) {
            // TODO Auto-generated constructor stub
            product_name = (TextView) view.findViewById(R.id.prod_name);
            qty = (TextView) view.findViewById(R.id.qty);
            unit = (TextView) view.findViewById(R.id.unit);
        }

    }

   }
   }

xml file :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

   <ListView
    android:id="@+id/phlist"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 </ListView>

</LinearLayout>
1

2 Answers 2

1

This is the problem caused by the position at which click is not the same position after the scroll on ListView you can easily fix this by allowing your object to remember if it was selected by Onclick listnere

Assume this is the class you have whose type of list you have provided to the Adapter

class ProductInfo{
  // here you already have your instance variables 

  boolean isSelected;
}

when you Onclick on an ProductInfo item make this instance variable of respective ProductInfo, true and change the background of the respective item in your Adapter which you must have extended from ArrayAdapter or BaseAdapter.

when you populate your List in ListView's adapter what you can check is if the isSelected is true than make respective item's background selected . otherwise don't

by doing so you will be independent of the position of the item with respective of the scroll. So your ProductInfo will retain the background change which was actually selected.

Update,

I am still right so i wrote a code snippet with output that you may check, I have kept the code as simple as I can and wrote things in single file for simplicity, and the code is also available on github, where you check code properly

public class CustomListViewActivity extends Activity {

    private ListView listView;
    private ArrayList<ProductInfo> productInfos;
    private ArrayAdapter<ProductInfo> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_list_view2);

        initializeUI();
    }

    private void initializeUI() {

        listView = (ListView)findViewById(R.id.CustomListViewActivity_listView_two);

        productInfos = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            ProductInfo productInfo = new ProductInfo();
            productInfo.setText("Product_1_"+i);
            productInfos.add(productInfo);
        }

        adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_custom_one, productInfos);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProductInfo productInfo = (ProductInfo) listView.getItemAtPosition(position);
                productInfo.setSelected(true);
                adapter.notifyDataSetChanged();
            }
        });

    }


    private class MyAdapter extends ArrayAdapter {

        private ArrayList<ProductInfo> a_productInfos;
        private Context a_context;
        private LayoutInflater a_layoutInflater;

        public MyAdapter(Context context, int resource, ArrayList<ProductInfo> a_productInfos) {
            super(context, resource, a_productInfos);
            this.a_productInfos = a_productInfos;
            this.a_context = context;
            a_layoutInflater = LayoutInflater.from(this.a_context);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder holder = null;
            if (row == null) {
                row = a_layoutInflater.inflate(R.layout.single_item_custom_one, parent, false);
                holder = new ViewHolder();
                holder.product_name = (TextView) row.findViewById(R.id.single_item_custom_one_textView);
                holder.item_LinearLayout = (LinearLayout) row.findViewById(R.id.single_item_custom_one_linearLayout);
                row.setTag(holder);
            } else {
                holder = (ViewHolder) row.getTag();
            }

            final ProductInfo productInfo = a_productInfos.get(position);
            holder.product_name.setText(""+productInfo.getText());

            if (productInfo.isSelected) {
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ff44ff"));
            }else {
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
            }

            return row;
        }

        class ViewHolder {
            TextView product_name;
            LinearLayout item_LinearLayout;
        }

        @Override
        public int getCount() {
            return super.getCount();
        }
    }

    private class ProductInfo {
        private String text;
        private boolean isSelected;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
}

activity_custom_list_view2.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/CustomListViewActivity_listView_two"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

single_item_custom_one.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/single_item_custom_one_linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView

        android:id="@+id/single_item_custom_one_textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
        android:paddingRight="?android:attr/listPreferredItemPaddingRight"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="#000" />
</LinearLayout>

Output

output_image

2
0

Update the code

if (arrayListProf.get(position).isOngoing() && mselected ==position) {
        convertView.setBackgroundColor(Color.parseColor("#ff0000"));
         convertView.setTag(vh);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.