Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on recyclerview item

I really want to set focus on a specific RecyclerView item. I tried

recyclerView.scrollToPosition(1);

in my initializeRecyclerView method. I tried also

holder.setSelected(selectedItem==position)

without success.

Can you please help me ?

Here is my Adapter:

 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.radio_item, parent, false);
    return new ViewHolder(v);
}

/**
 * Set the properties of a RecyclerView item
 * @param holder RecyclerView item
 * @param position Position of the item in the items list
 */
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    Radio radio = radios.get(position);
    holder.radio = radio;
    ImageHelper.setImage(context, holder.imageButton, radio.getLogoPath(), context.getDrawable(Const.DEFAULT_RADIO_LOGO_DRAWABLE) );
    holder.imageButton.setBackground(context.getDrawable(R.drawable.button));
    holder.imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                clickListener.onRadioClick(holder.getAdapterPosition());
            }
        }
    });
}
public class ViewHolder extends RecyclerView.ViewHolder{
    private ImageButton imageButton;
    public Radio radio;

    private ViewHolder(View itemView) {
        super(itemView);
        imageButton = itemView.findViewById(R.id.radioButton);
    }
}

And in my Fragment:

if(getView()!=null){
        RadiosAdapter recyclerAdapter = new RadiosAdapter(radios, getActivity());
        RecyclerView recyclerView = getView().findViewById(R.id.radios_recycler);
        recyclerView.setAdapter(recyclerAdapter);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), columnNumber, LinearLayoutManager.VERTICAL, false));
        if(currentRadio !=null){
            recyclerView.scrollToPosition(currentRadio.getPosition());
        }
        else{
            recyclerView.scrollToPosition(1);
        }

        if(getActivity() != null && getActivity() instanceof OnClickListener){
            OnClickListener listener = (OnClickListener)getActivity();
            recyclerAdapter.setClickListener(listener);
        }
    }

Thanks !

like image 504
Edwin ZAP Avatar asked Nov 27 '17 22:11

Edwin ZAP


1 Answers

using requestFocus() might solve your problem. but if not, I solved the same kind of a problem via,

in adapter I override the OnViewAttachedToWindow() and in there I called requestFocus() when ViewHolder is the matching the item.

Reference - https://stackoverflow.com/a/41232962/7616455

like image 79
RochaaP Avatar answered Nov 17 '22 08:11

RochaaP