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 !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With