Question

I'm using a custom ListFragment to display a list in which even rows have a background and odd rows don't. To do this I made a subclass of ArrayAdapter with an overriden getView(int, View, ViewGroup) method and set the background resource for the even rows there.

It worked, but I needed to adjust the dimensions of the views to be equal in the rows with and without background, so I adjusted the LayoutParams as follows:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    if ((position & 1) == 0) {
        view.setBackgroundResource(R.drawable.marcador_wink_normal);
    }
    ViewGroup.LayoutParams params = view.getLayoutParams();
    params.height = rowHeight;
    view.setLayoutParams(params);
    return view;
}

I tried this, and it seemed to work until I scrolled down and then up, which resulted in the background being applied to every row.

My question is: what am I doing wrong?

I'm using the v4 support library for the fragments, and this is the onCreate(Bundle) method of my custom ListFragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    setListAdapter(new WinkAdapter(getActivity(), layout, TEST_LIST));
}
Was it helpful?

Solution

The View used to make up the list are reused once they aren't visible on the screen.

In your original code, once the background was set to R.drawable.marcador_wink_normal on a given View, it was R.drawable.marcador_wink_normal forever. When you added the else, you made it set the background correctly on these reused Views.

OTHER TIPS

Okay, I solved it just adding an else statement:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    if ((position & 1) == 0) {
        view.setBackgroundResource(R.drawable.marcador_wink_normal);
    }
    else {
        view.setBackgroundColor(0);
    }
    ViewGroup.LayoutParams params = view.getLayoutParams();
    params.height = 100;
    view.setLayoutParams(params);
    return view;
}

But I still don't understand why the problem happened.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top