0

I have a ListView with custom adapter and I want to change the background color of an item. I used this code:

 @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final Holder holder = new Holder();
        final View rowView;
        rowView = inflater.inflate(R.layout.program_list, null);
        holder.tv = (TextView) rowView.findViewById(R.id.textView1);
        holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
        holder.tv.setText(result[position]);
        holder.img.setImageResource(imageId[position]);
        rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position != 0) {
                    rowView.setBackgroundColor(Color.rgb(70, 190, 200));
                }
            }
        });
        return rowView;
    }

It is working fine, but my question is - how can I change the next item color within the onclick function with knowing the last item will not get pressed(causing out of bounds error)? (If I press the item at position 4, then change the background color of position 5).

          rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            // ?
            }
        });

Thanks :)

DAVIDBALAS1
  • 484
  • 10
  • 31
  • refer http://stackoverflow.com/questions/16453379/android-list-adapter-returns-wrong-position-in-getview – sasikumar Apr 16 '16 at 12:03

1 Answers1

1

If you declare myListView as a member variable in your adapter, and in your getView method initialize it as

this.myListView = (ListView) parent;

then you get the position of the currently selected item in your onClick method by

int currPos = MyCustomAdapter.this.myListView(getPositionForView((View) view.getParent()));

Up to this point, I have used this code myself, and it works. Now, according to the Android Javadoc, the following expression should yield the next view:

MyCustomAdapter.this.myListView(getChildAt(currPos + 1)).

You should then be able to do whatever you want with that view, but I haven't tested this part yet.

TAM
  • 1,731
  • 13
  • 18