Sunday, May 8, 2011

Hiding an entry of a list

When using a cursor adapter, like for instance the SimpleCursorAdapter, we can sometime have special row of data that we don't want to display. To remove those undesirable entry, one only need to set the visibility to gone when the specific row is bonded.

To do that, the class SimpleCursorAdapter need to be extended with a custom bindView method like the following:
@Override
public void bindView(View inView, Context inContext, Cursor inCursor) {
    super.bindView(inView, inContext, inCursor);
                   
    TextView lNameView =  (TextView) inView.findViewById(R.id.name);
    if(lNameView.getText().toString().equals("Name entry to be hidden")) {
        //Set the layout to gone
        inView.setVisibility(View.GONE); 
        //Go through all row layout child and set visibility to gone
        for(int i = 0; i < ((ViewGroup) inView).getChildCount(); ++i) {
            ((ViewGroup) inView).getChildAt(i).setVisibility(View.GONE);
        }
    }
}
In this custom binding method, the row is detected by a match on the name column. Then, the row layout and its childs have their visibility set to View.Gone. If only the row layout is set to gone, then the row will still have a defined height. The row completely disappear only if all the child are also set to gone.

While this code is enough to hide a line, it's not enough to ensure that all the line we want to keep are not hidden. In fact, when the view is reused later, the visibility property could still be set to gone for a line that should in fact have a visible state. Therefore, the following code is needed to ensure the correct visible state of all lines.
@Override
public void bindView(View inView, Context inContext, Cursor inCursor) {
    super.bindView(inView, inContext, inCursor);
                   
    TextView lNameView =  (TextView) inView.findViewById(R.id.name);
    if(lNameView.getText().toString().equals("Name entry to be hidden")) {
        //Set the layout to gone
        inView.setVisibility(View.GONE); 
        //Go through all row layout child and set visibility to gone
        for(int i = 0; i < ((ViewGroup) inView).getChildCount(); ++i) {
            ((ViewGroup) inView).getChildAt(i).setVisibility(View.GONE);
        }
    } else {
        //Set the layout to visible
        inView.setVisibility(View.VISIBLE);
        for(int i = 0; i < ((ViewGroup) inView).getChildCount(); ++i) {
            //Go through all row layout child and set visibility to visible
            ((ViewGroup) inView).getChildAt(i).setVisibility(View.VISIBLE);
        }
    }
}

1 comment:

  1. Many thanks. The tip to hide children view saved me headache.

    ReplyDelete