BST Kaal
BST Kaal

Reputation: 3033

Show FastScroll only if the list data is enough to be scrolled

I have a ListView and i need to turn the visibility of FastScroll always enabled. The issue is, when the list items are only a few (say only 2 or 3) and easily to be fitted on screen, obviously they can't be scrolled. But the FastScroll is still on screen i.e visible. How can i disable it or hide it when the list items are fewer than to be scrollable.

enter image description here

Upvotes: 1

Views: 103

Answers (2)

MinceMan
MinceMan

Reputation: 7592

Don't listen to @Ridcully. Default behavior is rarely optimal and this isn't too hard to do. The following method does require that you know your item height. This also has your activity implement OnPreDrawListener.

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

    listView = (ListView) findViewById(R.id.list);
    itemViewHeight = getResources().getDimensionPixelSize(R.dimen.item_height);

    adapter = new YourAdapterClass();
    listview.setAdapter(adapter);

    ViewTreeObserver vto = list.getViewTreeObserver();
    if (vto != null && list.getMeasuredHeight() == 0) {
        vto.addOnPreDrawListener(this);
    } else if (list.getMeasuredHeight() != 0) {
        listViewHeight = list.getMeasuredHeight();
    }
}

public void setData(Object data) {
    // Set your adapter data how ever you do.
    adapter.setData(data);
    handleFastScrollVisibility();
}

private void handleFastScrollVisibility() {
    if (listViewHeight == 0 || list == null) return;

    int itemCount = adapter.getCount();
    int totalItemHeight = itemCount * itemViewHeight;

    list.setFastScrollAlwaysVisible(totalItemHeight > listViewHeight);
}

@Override
public boolean onPreDraw() {
    ViewTreeObserver vto = list.getViewTreeObserver();
    if (vto != null) vto.removeOnPreDrawListener(this);

    listViewHeight = list.getMeasuredHeight();
    handleFastScrollVisibility();

    return true;
}

Basicly you don't know when the height of the ListView is going to be ready. That's why you add a predraw listener, it will notify you when it is ready. I don't know how you get your data but this method assumes that you don't know if your ListView height or your data will be ready first. How you add data to your adapter will be depend on your adapter.

Upvotes: 1

Ridcully
Ridcully

Reputation: 23665

You can enable/disable the fast scroll feature programmatically via the setFastScrollEnabled(boolean) method.

So just check how many entries your list has, and enable/disable fast scroll accordingly.

Upvotes: 1

Related Questions