java - ListView 项目选择的背景改变了,它也改变了其他项目

标签 java android listview

我是 ListView 中的新手,我想在 ListView 上单击项目,它会更改背景颜色,它会更改,但滚动后我也会更改其他项目背景 View 。我找不到我哪里错了?

代码 fragment : 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 上滚动后点击的位置不在同一个位置引起的问题你可以通过让你的对象记住它是否被 选择来轻松解决这个问题点击 listnere

假设这是您拥有的类,您已将其类型的 list 提供给 Adapter

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

  boolean isSelected;
}

当您在 ProductInfo 项上Onclick 时,使相应 ProductInfo 的此实例变量为 true 并更改Adapter 中相应项目的背景,您必须从 ArrayAdapterBaseAdapter 扩展它。

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

通过这样做,您将独立于滚动条的相应位置。因此,您的 ProductInfo 将保留实际选择的背景更改。

Update,

我仍然是对的,所以我写了一个带有输出的代码 fragment ,您可以检查一下, 为了简单起见,我尽可能地保持代码简单,并在单个文件中编写内容,代码也可在 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 - ListView 项目选择的背景改变了,它也改变了其他项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34741895/

相关文章:

c# - 如何正确绑定(bind)和更新 Xamarin.Forms ListView?

每个时间线之间的 Javafx 暂停 "cycle"

java - 为什么这个时间单位转换返回零?

java - 如何避免在 Android(或任何 Java)项目中包含未使用的库?

android - 在 android 中使用 recyclerView 进行分页

android - Android 中错误的复选框选择?

java - Firebase 实时数据库

Java JLabel 多行高度

android - 警报对话框选项之间的分隔符

滚动 ListView 时Android ActionBar隐藏/显示