Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to given position in Android Leanback ListRow

I'm using the Google Leanback widgets in an Android TV application. It utilizes a RowsFragment with ListRows in it.

What I'm trying to determine is if there is any way to programmatically scroll to a particular object within one of the rows. I've dug into the docs for the Leanback widgets but cannot find what I'm looking for.

like image 765
ebr Avatar asked May 01 '15 21:05

ebr


3 Answers

I had a similar necessity: I needed to set the initial selected item in a ListRow. I ended up subclassing the ListRowPresenter like this:

import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.RowPresenter;

public class CustomPresenter extends ListRowPresenter {

    private int mInitialSelectedPosition;

    public CustomPresenter(int position) {
        this.mInitialSelectedPosition = position;
    }

    @Override
    protected void onBindRowViewHolder(RowPresenter.ViewHolder holder, Object item) {
        super.onBindRowViewHolder(holder, item);

        ViewHolder vh = (ListRowPresenter.ViewHolder) holder;
        vh.getGridView().setSelectedPosition(mInitialSelectedPosition);
    }

}

Hopefully this will help you.

like image 196
GerryP Avatar answered Nov 17 '22 05:11

GerryP


In the latest version of Leanback (think v23.3.0+), you can now specify not only the row position but also perform optional tasks on the row. In your case, the task would be programmatic selection like so:

BrowseFragment.setSelectedPosition(0, true, new ListRowPresenter.SelectItemViewHolderTask(2));

No need to implement custom list row presenters or anything

like image 21
kip2 Avatar answered Nov 17 '22 06:11

kip2


I've done it when I needed to implement "Return to the first item in a Row by pressing Back".

I was calling this method from Activity's onBackPressed().

If this method returns false we call Activity.super.onBackPressed(). If true - we don't.

    public boolean onBackPressed(){
        boolean consumeBack;

        int selectedRowPosition = getRowsFragment().getSelectedPosition();

        ListRowPresenter.ViewHolder selectedRow = (ListRowPresenter.ViewHolder) getRowsFragment().getRowViewHolder(selectedRowPosition);
        int selectedItemPosition = selectedRow.getSelectedPosition();

        if(selectedItemPosition == 0){
            consumeBack = false;
        } else {
            consumeBack = true;
            getRowsFragment().setSelectedPosition(selectedRowPosition, true, new ListRowPresenter.SelectItemViewHolderTask(0));
        }
        return consumeBack;
}

Instead of "0" you can set any position you need.

like image 6
Danylo Volokh Avatar answered Nov 17 '22 05:11

Danylo Volokh