java-列表视图项的选定背景已更改,它也会更改其他项

我是列表视图中的新手,我想在列表视图上单击它会更改背景颜色,它会更改,但是在滚动后我也会更改其他项目背景视图.我找不到我错了吗?

代码段:
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文件:

<?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>
最佳答案
这是由于在ListView上滚动后单击位置与单击位置不同而导致的问题,您可以通过让对象记住是否由Onclick listnere选择了对象来轻松解决此问题.

假设这是您提供给适配器的列表类型的类

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

  boolean isSelected;
}

当您在ProductInfo项上单击时,将其对应的ProductInfo的实例变量设为true,并更改您必须已从ArrayAdapter或BaseAdapter扩展的Adapter中的相应项的背景.

当您在ListView的适配器中填充List时,可以检查isSelected是否为true,而不是选择相应项目的背景.否则不要

这样,您将与滚动条无关地独立于项目的位置.因此,您的ProductInfo将保留实际选择的背景更改.

Update,

我还是对的,因此我写了一个代码段,其中包含您可以检查的输出,
为了使代码更加简洁,我将代码保持了尽可能的简单,并且在单个文件中编写了代码,并且代码也可以在github上使用,您可以在其中正确检查代码

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

转载注明原文:java-列表视图项的选定背景已更改,它也会更改其他项 - 代码日志