Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Android RecyclerView (GridLayoutManager) focus behavior

I have a RecyclerView with GridLayoutManager, with 2 columns per row. Because the develop is for Android TV so that I need focus to navigate.

enter image description here

It's ok if I'm using down key to navigate to any visible items. For example, Item 1 -> Item 3 -> Item 5 -> Item 7 (Only partially visible.). But when I press down key again, the focus will move to Item 10 instead of 9.

enter image description here

My grid view adapter is:

public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {    
    private ArrayList<String> mDataset;

    public GridAdapter(ArrayList<String> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.grid_item, viewGroup, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.txtTitle.setText(mDataset.get(position));    
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView txtTitle;
        public ViewHolder(View v) {
            super(v);
            txtTitle = (TextView) v.findViewById(R.id.title);
        }
    }
}

Any idea how to solve this issue? Thanks.

like image 537
Bagusflyer Avatar asked Jan 23 '15 04:01

Bagusflyer


1 Answers

View this related post and Vganin's answer for resolve your problem.

I reported this bug to AOSP issue tracker: issue 190526

As I can see from source the issue is because GridLayoutManager uses LinearLayoutManager's implementation of onFocusSearchFailed() which is called when focus approaches the inner border of RecyclerView. LinearLayoutManager's implementation just offers first/last (depends on scrolling direction) element. Hence focus jumps to first/last element of new row.

My workaround for this issue.

like image 188
Crisic Avatar answered Nov 15 '22 16:11

Crisic