Question

I want to limit the listview's open items to one. How do I close the previous opened item, when another item is clicked?

For example: Item #1 is clicked - Item #1 opens.
Item #2 is clicked - Item #1 closes. Item #2 opens.

I tryed to call the onItemClick function manually with the last position, but it's too complexed.

Here's my onitemclick function:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        animSlideDown = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.slide_down);
        RelativeLayout wrapper = (RelativeLayout) view;
        final RelativeLayout itemClosed = (RelativeLayout) wrapper.getChildAt(1);
        final RelativeLayout fullItem = (RelativeLayout) wrapper.getChildAt(0);
        boolean isOpen = itemClosed.getVisibility() == View.GONE;


        if (!isOpen) {
            fullItem.setVisibility(View.VISIBLE);
            fullItem.startAnimation(animSlideDown);
            itemClosed.setVisibility(View.GONE);
        } else {
            itemClosed.setVisibility(View.VISIBLE);
            fullItem.setVisibility(View.GONE);
        } 
    }

Thanks

Was it helpful?

Solution 2

Answering my own question - It was actually very simple, all I had to do was to go through each child of "parent" and hide it if it's not the current view. hope it'll help someone one day..

    @Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    RelativeLayout wrapper = (RelativeLayout) view;
    final RelativeLayout itemClosed = (RelativeLayout) wrapper.getChildAt(1);
    final RelativeLayout fullItem = (RelativeLayout) wrapper.getChildAt(0);
    boolean isOpen = itemClosed.getVisibility() == View.GONE;

    if (!isOpen) {
        fullItem.setVisibility(View.VISIBLE);
        itemClosed.setVisibility(View.GONE);

        for (int i = 0; i < parent.getChildCount(); i++) {
            RelativeLayout v = (RelativeLayout) parent.getChildAt(i);
            if (v != view && v.getChildAt(0).getVisibility() == View.VISIBLE) {
                v.getChildAt(0).setVisibility(View.GONE);
                v.getChildAt(1).setVisibility(View.VISIBLE);
            }
        }

    } else {
        itemClosed.setVisibility(View.VISIBLE);
        fullItem.setVisibility(View.GONE);
    }
}

OTHER TIPS

use Expandable List View for this purpose. to implement your logic, best option is Expandable List View.

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