Android: first item list view acting weird

In my Android application, I have a ListView with 5 items. I created a custom adapter to change the background of some listView elements. For example, the second element of the list is not ready yet, so I want setBackground(Color.Gray) , so it may look like it wasn’t. To do this, I redefined the getView () method from the ArrayAdapter in my user adapter, as follows:

 @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if(!itensAvailable[position]) v.setBackgroundColor(Color.Gray); return v; } 

Strange, whether I use a logical itensAvailable[position] or !itensAvailable[position] , the first list item always changes the background! All other elements of the list behave as expected, except for the first. More strange if I do this if(position == 2) v.setBackgroundColor(Color.Gray);

it changes the background from position in position 2 to the first element! If i do

 if(position == 2) { v.setBackgroundColor(Color.Gray); System.out.println(v.getText()); } 

More weird! Only text from position 2 is printed, not text from the first element.

What's happening? Android bug? By the way, I tested it on a XOOM 3.2 Honeycomb device.

And, obviously, if I comment on this code, the first element will not change it.

+4
source share
3 answers

It is very strange! What happens if you write:

  @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if(!itensAvailable[position]) v.setBackgroundColor(Color.Gray); else v.setBackgroundColor(Color.Transparent); return v; } 
+2
source

I can not explain the strange behavior. Can you try the following code and see if it solves your problem -

 @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = to the view to be displayed; } if(!itensAvailable[position]) convertView.setBackgroundColor(Color.Gray); return convertView; } 
0
source

I have exactly the same problem. Weird!

What worked for me is to delete the line

 View v = super.getView(position, convertView, parent); 

and use instead

 LayoutInflater inflater = LayoutInflater.from(getContext()); View v = inflater.inflate(R.layout.__my__layout__, parent, false); .... more view manipulations .... 

hope this helps!

0
source

Source: https://habr.com/ru/post/1383067/


All Articles