androidandroid-listviewandroid-fragmentsandroid-listfragmentfastscroll

How to enable fast scrolling for a ListFragment?


I use a fragment activity to hold a list fragment which renders a bunch of products:

public class ProductsListActivity extends SherlockFragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Sherlock___Theme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_products_list);
        // setFastScrollEnabled(true) ?
    }
}

...

<!-- fragment_products_list.xml -->
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.example.fragment.ProductsListFragment"
    android:id="@+id/list_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

...

public class ProductsListFragment extends SherlockListFragment {

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // setFastScrollEnabled(true) ?
        super.onViewCreated(view, savedInstanceState);
    }

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

I want to enable fast scrolling for the list of products and found another post which describes how to do this for a list activity. But how can I activate fast scrolling for the fragment? It would be okay to define this in XML or via code.


Solution

  • The SherlockListFragment also has a getListView() method inherited from ListFragment.

    getListView().setFastScrollEnabled(true);
    

    This is how it could look like inside your ListFragment:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    
        ArrayList<String> strings = new ArrayList<String>();
    
        for(int i = 0; i < 300; i++) strings.add("Item " + i);
    
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strings);
        setListAdapter(adapter);
    
        getListView().setFastScrollEnabled(true);
    }