Android TV. Adding custom views to VerticalGridFragment

I am building an Android TV app and want to add some views to VerticalGridFragment. Is that possible and how?

I am using leanback library version 25.0.0. Thank you for all the answers.

Upvotes: 1

Views: 2609

Answers (1)

Kyle Venn
Kyle Venn

Reputation: 8038

The leanback-showcase example provided by the leanback team has a great example on how to do this. I highly recommend you clone that repo and play around in that project.

You'll basically want to initialize an Adapter with a Presenter that knows how to present the views you'd like to display in your list. This class right here has a specific example of exactly what you're looking for.

In the example they use a PresenterSelector, but if your list is homogenous (backed by only one model), then you can pass in a single Presenter directly into the Adapter - like the Presenter here.

In code - first setup your grid presenter

VerticalGridPresenter gridPresenter = new VerticalGridPresenter(ZOOM_FACTOR);
gridPresenter.setNumberOfColumns(COLUMNS);
setGridPresenter(gridPresenter);

Then set your adapter on the VerticalGridFragment

PresenterSelector cardPresenterSelector = new CardPresenterSelector(getActivity());
mAdapter = new ArrayObjectAdapter(cardPresenterSelector);
setAdapter(mAdapter);

Then add models to your Adapter

private void createRows() {
    String json = Utils.inputStreamToString(getResources()
            .openRawResource(R.raw.grid_example));
    CardRow row = new Gson().fromJson(json, CardRow.class);
    mAdapter.addAll(0, row.getCards());
}

Upvotes: 1

Related Questions