选择背景改变列表视图项,它也改变了其他项目 [英] list view item selected background changed , it changes other item also

查看:117
本文介绍了选择背景改变列表视图项,它也改变了其他项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我M在列表视图中新,我想项目单击列表视图它改变背景颜色,改变它,但我之后滚动它改变了其他项目的背景观点也。我无法找出我错了?

code片断:
ListColorChange.java

 包com.example.spinnerfilter; 公共类ListColorChange延伸活动{ 私人的ListView phproductinfo;
 ArrayList的< ProductInfo> arrayListProf;
ChangeColorAdapter适配器;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);    的setContentView(R.layout.demo);    在里面();
}INT mselected = -1;公共无效的init(){    phproductinfo =(ListView控件)findViewById(R.id.phlist);    arraylistInit();    适配器=新ChangeColorAdapter(ListColorChange.this,arrayListProf);    phproductinfo.setAdapter(适配器);    phproductinfo.setOnItemClickListener(新OnItemClickListener(){        @覆盖
        公共无效onItemClick(适配器视图<>为arg0,ARG1查看,
                INT位置,长ARG3){
            // TODO自动生成方法存根
            mselected =位置;
            ProductInfo信息= arrayListProf.get(位置);            info.setOngoing(真);            adapter.notifyDataSetChanged();        }
    });}私人无效arraylistInit(){    字符串名称[] = {印度,Austrai,Xyxz,帕斯克,新,印度,
            Austrai,Xyxz,帕斯克,新,印,Austrai,Xyxz,
            帕斯克,新,印度,Austrai,Xyxz,帕斯克,新
            印度,印度,Austrai,Xyxz,帕斯克,新,印度,
            印度,Austrai,Xyxz,帕斯克,新,印度,印度,
            Austrai,Xyxz,帕斯克,新,印};
    arrayListProf =新的ArrayList< ProductInfo>();
    的for(int i = 0; I< name.length;我++){
        ProductInfo信息=新ProductInfo();        info.setDisplay_name(名称[I]);
        info.setOngoing(假);        arrayListProf.add(信息);
    }}   公共类ChangeColorAdapter延伸BaseAdapter   {    公共ChangeColorAdapter(ListColorChange listColorChange,
            ArrayList的< ProductInfo> arrayListProf){
        // TODO自动生成构造函数存根
    }    @覆盖
    公众诠释的getCount(){
        // TODO自动生成方法存根
        返回arrayListProf.size();
    }    @覆盖
    公共对象的getItem(INT为arg0){
        // TODO自动生成方法存根
        返回arrayListProf.get(为arg0);
    }    @覆盖
    众长getItemId(INT为arg0){
        // TODO自动生成方法存根
        返回将arg0;
    }    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中ARG2){
        // TODO自动生成方法存根
        ViewHolder VH;
        如果(convertView == NULL){
            LayoutInflater气筒= LayoutInflater
                    。从(ListColorChange.this);
            convertView = inflater.inflate(R.layout.productlist,NULL);
            TextView的PRODUCT_NAME =(TextView中)convertView
                    .findViewById(R.id.prod_name);
            VH =新ViewHolder(convertView);
            convertView.setTag(VH);
        }其他{
            VH =(ViewHolder)convertView.getTag();
        }
        如果(arrayListProf =空&放大器;!&放大器; arrayListProf.size()大于0){
            ProductInfo PI = arrayListProf.get(位置);
            如果(pi.getDisplay_name()!= NULL){
                vh.product_name.setText(pi.getDisplay_name());
            }
            如果(arrayListProf.get(位置).isOngoing()及&放大器; mselected ==位置){
                    convertView.setBackgroundColor(Color.parseColor(#FF0000));
            }
        }        返回convertView;
    }    类ViewHolder {
        TextView的PRODUCT_NAME;
        TextView的数量;
        TextView的单位;
        INT位置;        布尔ISPU = FALSE;        公共ViewHolder(查看视图){
            // TODO自动生成构造函数存根
            PRODUCT_NAME =(TextView中)view.findViewById(R.id.prod_name);
            数量=(TextView中)view.findViewById(R.id.qty);
            单位=(TextView中)view.findViewById(R.id.unit);
        }    }   }
   }

XML文件:

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直>   < ListView控件
    机器人:ID =@ + ID / phlist
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
 < /&的ListView GT;< / LinearLayout中>


解决方案

这是由在此点击不在的ListView滚动后的相同位置的位置问题你可以很容易地通过允许它是否是由的onclick listnere

选择记住你的对象,解决这个问题

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

 类ProductInfo {
  //在这里已经有你的实例变量  布尔isSelected;
}

的onclick 上的产品介绍项目作出相应的产品介绍<的这个实例变量/ code>,真正并更改相应项的背景在适配器,你必须扩展从 ArrayAdapter BaseAdapter

当您填充列表中的 ListView的适配器,你可以检查是什么,如果 isSelected 比让各自的真项目的背景选择。否则不

这样做,你将独立的项目与相应的滚动的位置。所以,你的产品介绍将保留它实际上选择的背景变化。


  

更新,


我还是正确的,所以我写了一个code段与您可以检查输出,
我一直在code一样简单,我可以和在简单单一的文件中写道的事情,和code,也可在<一href=\"https://github.com/pankajnimgade/Tutorial/blob/master/app/src/main/java/listview/test/activities/CustomListViewActivity.java\"相对=nofollow> github上,在那里你检查code正确

 公共类CustomListViewActivity延伸活动{    私人的ListView ListView的;
    私人的ArrayList&LT; ProductInfo&GT; productInfos;
    私人ArrayAdapter&LT; ProductInfo&GT;适配器;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_custom_list_view2);        initializeUI();
    }    私人无效initializeUI(){        ListView控件=(ListView控件)findViewById(R.id.C​​ustomListViewActivity_listView_two);        productInfos =新的ArrayList&LT;&GT;();
        的for(int i = 0; I&LT; 50;我++){
            ProductInfo productInfo =新ProductInfo();
            productInfo.setText(Product_1 _+ I);
            productInfos.add(productInfo);
        }        适配器=新MyAdapter(getApplicationContext(),R.layout.single_item_custom_one,productInfos);
        listView.setAdapter(适配器);        listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,INT位置,长的id){
                ProductInfo productInfo =(ProductInfo)listView.getItemAtPosition(位置);
                productInfo.setSelected(真);
                adapter.notifyDataSetChanged();
            }
        });    }
    私有类MyAdapter扩展ArrayAdapter {        私人的ArrayList&LT; ProductInfo&GT; a_productInfos;
        私人语境a_context;
        私人LayoutInflater a_layoutInflater;        公共MyAdapter(上下文的背景下,INT资源的ArrayList&LT; ProductInfo&GT; a_productInfos){
            超级(上下文,资源,a_productInfos);
            this.a_productInfos = a_productInfos;
            this.a_context =背景;
            a_layoutInflater = LayoutInflater.from(this.a_context);
        }
        @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){
            查看排= convertView;
            ViewHolder支架=无效;
            如果(行== NULL){
                行= a_layoutInflater.inflate(R.layout.single_item_custom_one,父母,假);
                持有人=新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(保持器);
            }其他{
                支架=(ViewHolder)row.getTag();
            }            最后ProductInfo productInfo = a_productInfos.get(位置);
            holder.product_name.setText(+ productInfo.getText());            如果(productInfo.isSelected){
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor(#ff44ff));
            }其他{
                holder.item_LinearLayout.setBackgroundColor(Color.parseColor(#FFFFFF));
            }            返回行;
        }        类ViewHolder {
            TextView的PRODUCT_NAME;
            的LinearLayout item_LinearLayout;
        }        @覆盖
        公众诠释的getCount(){
            返回super.getCount();
        }
    }    私有类ProductInfo {
        私人字符串文本;
        私人布尔isSelected;        公共字符串的getText(){
            返回文本;
        }        公共无效的setText(字符串文本){
            this.text =文本;
        }        公共布尔isSelected(){
            返回isSelected;
        }        公共无效的setSelected(布尔选择){
            isSelected =选择;
        }
    }
}


  

activity_custom_list_view2.xml


 &LT;的LinearLayout
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直&GT;    &LT; ListView控件
        机器人:ID =@ + ID / CustomListViewActivity_listView_two
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT/&GT;
&LT; / LinearLayout中&GT;


  

single_item_custom_one.xml


 &LT;?XML版本=1.0编码=UTF-8&GT?;
&LT; LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / single_item_custom_one_linearLayout
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:方向=垂直&GT;    &LT;的TextView        机器人:ID =@ + ID / single_item_custom_one_textView
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:重力=center_vertical
        安卓了minHeight =机器人:ATTR /列表preferredItemHeightSmall
        机器人:paddingEnd =机器人:ATTR /列表preferredItemPaddingEnd
        机器人:paddingLeft =机器人:ATTR /列表preferredItemPaddingLeft
        机器人:paddingRight =机器人:ATTR /列表preferredItemPaddingRight
        机器人:paddingStart =机器人:ATTR /列表preferredItemPaddingStart
        机器人:textAppearance =机器人:ATTR / textAppearanceListItemSmall
        机器人:文字颜色=#000/&GT;
&LT; / LinearLayout中&GT;


  

输出


output_image

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>

解决方案

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

这篇关于选择背景改变列表视图项,它也改变了其他项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆