How to call scrollToPosition(position) inside recyclerView's adapter? - java

I have a setOnClick listener inside my onBindViewHolder
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
((ViewHolder) holder).txtType.setText(object.text);
((ViewHolder) holder).checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, ""+position, Toast.LENGTH_SHORT).show();
//???.scrolltoPosition(position+1);
}
});
on click, I would be scrolling the viewport to the next recycler view item. I've done this inside my MainActivity java by recyclerView.scrollToPosition(position);. But inside Adapter Class on onBindViewHolder, I have no idea how to call my recyclerView on the Main Java Class.
How should I do this?
edit:
For simplification purposes, I revised this previous code, because I have used a multiview adapter for my recycler. Here is the multiview adapter:
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
private ArrayList<InstructionModel>dataSet;
Context mContext;
int total_types;
private LinearLayoutManager manager;
public MultiViewTypeAdapter(LinearLayoutManager manager)
{
this.manager=manager;
}
public static class SimpleTextViewHolder extends RecyclerView.ViewHolder {
TextView txtType;
CardView cardView;
CheckBox checkBox;
public SimpleTextViewHolder(View itemView) {
super(itemView);
this.txtType = (TextView) itemView.findViewById(R.id.type);
this.cardView = (CardView) itemView.findViewById(R.id.card_view);
this.checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
}
}
public static class TimeTextViewHolder extends RecyclerView.ViewHolder {
TextView txtType;
CardView cardView;
CheckBox checkBox;
public TimeTextViewHolder(View itemView) {
super(itemView);
this.txtType = (TextView) itemView.findViewById(R.id.type);
this.cardView = (CardView) itemView.findViewById(R.id.card_view);
this.checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
}
}
public MultiViewTypeAdapter(ArrayList<InstructionModel> data, Context context) {
this.dataSet = data;
this.mContext = context;
total_types = dataSet.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case InstructionModel.SIMPLE_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple, parent, false);
return new SimpleTextViewHolder(view);
case InstructionModel.TIME_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.time, parent, false);
return new TimeTextViewHolder(view);
}
return null;
}
#Override
public int getItemViewType(int position) {
switch (dataSet.get(position).type) {
case 0:
return InstructionModel.SIMPLE_TYPE;
case 1:
return InstructionModel.TIME_TYPE;
default: return -1;
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {
InstructionModel object = dataSet.get(listPosition);
if (object != null) {
switch (object.type) {
case InstructionModel.SIMPLE_TYPE:
((SimpleTextViewHolder) holder).txtType.setText(object.text);
break;
case InstructionModel.TIME_TYPE:
((TimeTextViewHolder) holder).txtType.setText(object.text);
break;
}
}
}
#Override
public int getItemCount() {
return dataSet.size();
}
P.S.
If you see some random useless stuff, I was trying something.

Pass the LayoutManger with constuctor
class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private LinearLayoutManager manager;
public Adapter(LinearLayoutManager manager)
{
this.manager=manager;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
((ViewHolder) holder).txtType.setText(object.text);
((ViewHolder) holder).checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, ""+position, Toast.LENGTH_SHORT).show();
manager.scrollToPosition(position+1);
}
});
}

I think you should define a interface to notify your parent RecyclerView to do scroll operation, the RecyclerView into ViewHodler inside operation, resulting in the coupling

You can pass a listener object in the constructor which implements by Fragment OR Activity.
/**
* item click interface of adapter
*/
public interface MultiViewTypeAdapterListener {
void onScroll(int position)
}
This interface implements by Fragment OR Activity
/**
* On Scroll Implement Method from adapter listener.
*
* #param position
*/
#Override
public void onScroll(int position) {
// Here you can call that method
recyclerview.scrolltoPosition(position)
}
Then you pass this listener in the constructor of the adapter.
private void buildRecyclerView() {
multiViewTypeAdapter = new MultiViewTypeAdapter(this);
recyclerView.setAdapter(multiViewTypeAdapter);
}
In the constructor, you can assign like this
private MultiViewTypeAdapterListener mMultiViewTypeAdapterListener;
public OfferAdapter(MultiViewTypeAdapterListener mMultiViewTypeAdapterListener) {
this.mMultiViewTypeAdapterListener = mMultiViewTypeAdapterListener
}
}
Now you can use this listener by setting click listener on anyViwe like this
((ViewHolder) holder).checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, ""+position, Toast.LENGTH_SHORT).show();
//???.scrolltoPosition(position+1);
mMultiViewTypeAdapterListener.onScroll(position+1);
}
});
It returns to call the method of onItemClick which implements this method.

private int getScrollRange() {
int scrollRange = 0;
if (parent.getChildCount() > 0) {
View child = parent.getChildAt(0);
scrollRange = Math.max(0,
child.getHeight() - (parent.getHeight()));
}
return scrollRange;
}
ScrollView parent=findViewById(R.id.scroll_Recipe_Detail);
parent.scrollTo(0,getScrollRange());

if you want to scroll on new items added, you must override "onItemsAdded".
Here is how I did it:
recyclerView.apply {
setHasFixedSize(true)
layoutManager = MyLinearLayoutManager(this#MainActivity)
...
}
private class MyLinearLayoutManager(private val context: Context) :
LinearLayoutManager(context) {
// Force new items appear at the top
override fun onItemsAdded(recyclerView: RecyclerView, positionStart: Int, itemCount: Int) {
super.onItemsAdded(recyclerView, positionStart, itemCount)
scrollToPosition(findLastVisibleItemPosition())
}
}

Related

Recycleview cardview Onclick duplicate effects when scrolling

I'm making my first app (calendar),
clicking the cardview item applies the same effect (changing Textview text color and Imageview background) to other items when scrolling the recycleview
in the main activity
RecyclerView daysRecyclerView;
DaysAdapter daysAdapter;
private RecyclerView.LayoutManager horizontalLayout;
ArrayList<DaysModel> daysModels;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
daysModels = getDaysList();
initDaysRecycleview();
}
private void initDaysRecycleview(){
daysRecyclerView = findViewById(R.id.daysRecyclerView);
daysRecyclerView.setHasFixedSize(true);
horizontalLayout = new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false);
daysAdapter = new DaysAdapter(daysModels);
daysRecyclerView.setLayoutManager(horizontalLayout);
daysRecyclerView.setAdapter(daysAdapter);
daysAdapter.setOnItemClickListener(new DaysAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
dayClickHandler(position, 1);
}
});
}
public void dayClickHandler(int position, int change){
daysModels.get(position).changeDayHighlight(change);
daysAdapter.notifyItemChanged(position);
}
private ArrayList<DaysModel> getDaysList(){
//Not accurate used for testing
ArrayList<DaysModel> models = new ArrayList<DaysModel>();
String[] dayName ={"SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON"};
int i,j;
for (i = 0;i <dayName.length;i++){
j =i+1;
models.add(new DaysModel(dayName[i], j, 0, false));
}
return models;
}
I'm using an interface for the onClickListener.
ViewHolder
public class DaysViewHolder extends RecyclerView.ViewHolder {
TextView hDayName,hDayNumber;
ImageView currentDayHighlight;
CardView dayCard;
public DaysViewHolder(View itemView, DaysAdapter.OnItemClickListener listener) {
super(itemView);
this.hDayName = itemView.findViewById(R.id.dayName);
this.hDayNumber = itemView.findViewById(R.id.dayNumber);
this.currentDayHighlight = itemView.findViewById(R.id.dayHihlight);
this.dayCard = itemView.findViewById(R.id.dayCard);
dayCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
Adapter
public class DaysAdapter extends RecyclerView.Adapter<DaysViewHolder> {
Context context;
ArrayList<DaysModel> daysModels;
OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public DaysAdapter(ArrayList<DaysModel> daysModels) {
this.daysModels = daysModels;
}
#NonNull
#Override
public DaysViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.day_card,parent,false);
DaysViewHolder daysViewHolder = new DaysViewHolder(view, mListener);
return daysViewHolder;
}
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return daysModels.size();
}
}
sorry for the long code text, I've just started and I am already struggling.
All you need is to set else part for you if condition in bind method of Adapter class.
So change your bind method to something like this:
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}else{
holder.currentDayHighlight.setBackgroundResource(/*what ever you want for default situation*/);
holder.hDayNumber.setTextColor(/* for example Color.White*/);
}
}

Multiple OnClickListeners in Fragment with CustomAdapter

Problem: I am trying to implement three different OnClickListeners via floating action buttons into every item of a recycler view. Each of the three FABs does something different so they need different OnClickListeners. I think I am able to instantiate one with my current adapter setup, but I would like to be able to access all three in the fragment via something like this:
mRecyclerView2.addItemDecoration(itemDecoration2);
mLayoutManager2 = new GridLayoutManager(mContext, 3);
mRecyclerView2.setLayoutManager(mLayoutManager2);
mAdapter2 = new photo_adapter2(mContext, arrayList2);
mRecyclerView2.setAdapter(mAdapter2);
mAdapter2.floatingActionButtonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = mRecyclerView2.getChildAdapterPosition(v);
photo_item2 item = mAdapter2.getDataSet().get(position);
final String key = item.getMatchId();
}
});
mAdapter2.floatingActionButtonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = mRecyclerView2.getChildAdapterPosition(v);
photo_item2 item = mAdapter2.getDataSet().get(position);
final String key = item.getMatchId();
}
});
mAdapter2.floatingActionButtonChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = mRecyclerView2.getChildAdapterPosition(v);
photo_item2 item = mAdapter2.getDataSet().get(position);
final String key = item.getMatchId();
}
});
I get the following error when I move to the fragment:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.firetest.Tabs.MatchProcess.MatchFragment.onCreateView
Adapter:
public class photo_adapter2 extends RecyclerView.Adapter<photo_adapter2.ViewHolder> {
ImageView imageView;
FloatingActionButton floatingActionButtonDelete;
FloatingActionButton floatingActionButtonChat;
FloatingActionButton floatingActionButtonView;
private Uri imageUri;
private ArrayList<photo_item2> mDataSet;
private Context mContext;
private OnItemClickListener mListener;
public ArrayList<photo_item2> getDataSet() {
return mDataSet;
}
public void setDataSet(ArrayList<photo_item2> mDataSet) {
this.mDataSet = mDataSet;
}
public ImageView getImageView() {
return imageView;
}
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
public Context getContext() {
return mContext;
}
public void setContext(Context mContext) {
this.mContext = mContext;
}
public Uri getImageUri() {
return imageUri;
}
public void setImageUri(Uri imageUri) {
this.imageUri = imageUri;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public photo_adapter2(Context context, ArrayList<photo_item2> DataSet) {
mDataSet = DataSet;
mContext = context;
}
public ArrayList<photo_item2> DataSet() {
return mDataSet;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public FloatingActionButton floatingActionButtonDelete;
public FloatingActionButton floatingActionButtonView;
public FloatingActionButton floatingActionButtonChat;
public RelativeLayout mLinearLayout;
private int adapterPositionOnCLick;
public ViewHolder(View v, final OnItemClickListener listener) {
super(v);
mImageView = (ImageView) v.findViewById(R.id.tv);
floatingActionButtonDelete = (FloatingActionButton) v.findViewById(R.id.floatingActionButtonDelete);
floatingActionButtonChat = (FloatingActionButton) v.findViewById(R.id.floatingActionButtonChat);
floatingActionButtonView = (FloatingActionButton) v.findViewById(R.id.floatingActionButtonView);
floatingActionButtonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
adapterPositionOnCLick = getAdapterPosition();
if (adapterPositionOnCLick != RecyclerView.NO_POSITION) ;
listener.onItemClick(adapterPositionOnCLick);
}
}
});
floatingActionButtonChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
adapterPositionOnCLick = getAdapterPosition();
if (adapterPositionOnCLick != RecyclerView.NO_POSITION) ;
listener.onItemClick(adapterPositionOnCLick);
}
}
});
floatingActionButtonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
adapterPositionOnCLick = getAdapterPosition();
if (adapterPositionOnCLick != RecyclerView.NO_POSITION) ;
listener.onItemClick(adapterPositionOnCLick);
}
}
});
mLinearLayout = (RelativeLayout) v.findViewById(R.id.ll);
}
public ImageView getImageView() {
return mImageView;
}
public void setImageView(ImageView mImageView) {
this.mImageView = mImageView;
}
}
#Override
public photo_adapter2.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.photo_custom_view_card, parent, false);
ViewHolder vh = new ViewHolder(v, (OnItemClickListener) mListener);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final photo_item2 photo_item = mDataSet.get(position);
}
#Override
public int getItemCount() {
return mDataSet.size();
}
}
How would I go about creating three onClickListeners like this? How should I modify my current fragment and adapter set up to achieve that? Please let me know if there is anything else I should add to my post.
I think, you can create an interface onFabClickListener to dispatch the original onClick event on the FloatingActionButton to your Activity or Fragment. If three FloatingActionButtons are only way to interact with the row of RecyclerView, then I guess you don't even need to handle onItemClick()(or one which handle onclick of row overall).
The interface onFabClickListener.java may look like this :
// is supposed to handle every fab click of every viewholder
public interface OnFabClickListener {
// view to know which fab was click and position to know the position
// of viewholder that was clicked
void onFabClick(View view, int position);
}
Then your Adapter class may look like this :
public class photo_adapter2 extends RecyclerView.Adapter<photo_adapter2.ViewHolder> {
// you all other variable declarations
private ArrayList<photo_item2> mDataSet;
private Context mContext;
private OnFabClickListener mListener;
// your all other required methods definition
public void setOnFabClickListener(OnFabClickListener listener) {
mListener = listener;
}
public ArrayList<photo_item2> getDataSet() {
return mDataSet;
}
public void setDataSet(ArrayList<photo_item2> mDataSet) {
this.mDataSet = mDataSet;
}
public photo_adapter2(Context context) {
mContext = context;
}
#NonNull
#Override
public photo_adapter2.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.photo_custom_view_card, parent, false);
return new ViewHolder(v, mListener);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final photo_item2 photo_item = mDataSet.get(position);
// do you stuff here
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnFabClickListener listener;
public ViewHolder(View v, final OnFabClickListener listener) {
super(v);
// your all other view initialization
//setting our listener object
this.listener = listener;
// your all other views declaration
FloatingActionButton floatingActionButtonDelete = v.findViewById(R.id.floatingActionButtonDelete);
FloatingActionButton floatingActionButtonChat = v.findViewById(R.id.floatingActionButtonChat);
FloatingActionButton floatingActionButtonView = v.findViewById(R.id.floatingActionButtonView);
// setting onclicklisteners on them
// our view holder class is gonna handle all of the onclick
floatingActionButtonDelete.setOnClickListener(this);
floatingActionButtonChat.setOnClickListener(this);
floatingActionButtonView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
// if the view is a floating action button and listener is not equal to null
if (view instanceof FloatingActionButton && listener != null) {
if (getAdapterPosition() != RecyclerView.NO_POSITION) {
// for every on click listened here we will dispatch it to our activity or fragment which
// is required to respond to those events
listener.onFabClick(view, getAdapterPosition());
}
}
}
// your all other methods definition
}
}
Then now a sample MainActivity which implements our custom onFabClickListener will receive the appropriate onclick events handled and dispatched initially by our photo_adapter2 class may look like this:
public class MainActivity extends AppCompatActivity implements OnFabClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// declare and initialize the recyclerview
RecyclerView rcView = ......
// declare and initialize the requiredadapter
photo_adapter2 adapter = .....
// set the data using setDataSet() or you can skip this if you
// already passed the dataset in the constructor
adapter.setDataSet(yourDataSet);
// set this class as the onFabClickListener(you forgot this one I guess)
adapter.setOnFabClickListener(this);
// set the adapter to the recyclerview
rcView.setAdapter(adapter);
}
#Override
public void onFabClick(View view, int position) {
int id = view.getId();
switch (id) {
case R.id.floatingActionButtonDelete:
// you can now do your stuff here
break;
case R.id.floatingActionButtonChat:
// for eg get the item associated with the viewholder of whose fab was clicked
photo_item2 item = mAdapter2.getDataSet().get(position);
break;
case R.id.floatingActionButtonView:
break;
}
}
}
Note:
According to Material Design Specifications, it is not recommended to use more than one FloatingActionButton in the single screen(Activity/Fragment). It represents the most important single frequent action that is performed by the user. Instead, I think you should switch to MaterialButton and if you are using Fab just to get this circular look, you need to switch immediately. You can specify the materialButtonStyle attribute in your styles.xml file to get a circular look.
Check your XML file where all three floating action buttons are created, make sure you have them all created, with the respective names that you accessing from the view. The NullPointerException is telling you that one of your floating action button's are pointed to something that doesn't yet exist.

how to make the progress bar invisible in recyclerview

There is a list of pictures made through RecyclerView. When you click on a picture while it is being transferred to the next activity, a ProgressBar should be displayed. When there is a return to the activity of the image selection, the ProgressBar also remains visible, although it must be hidden.
As I did below, the progress bar becomes invisible only in the first image, but in the rest it does not work. I can’t understand why
in my project there are such classes as:
interface
public interface ImageOnC {
void onClick(int position);
}
ImageViewHolder
public class ImageViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
private ImageOnC imageOnC;
public ImageButton imageButton;
public ProgressBar progressBar;
public void setImageOnC(ImageOnC imageOnC) {
this.imageOnC = imageOnC;
}
public ImageViewHolder(#NonNull final View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_outline);
progressBar = itemView.findViewById(R.id.progr);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageOnC.onClick(getAdapterPosition());
progressBar.setVisibility(View.VISIBLE);
}
});
}
}
ImageAdabter
public class ImageAdabter extends RecyclerView.Adapter<ImageViewHolder> {
private Context mContext;
private List<Integer> listImages;
public ImageAdabter(Context mContext){
this.mContext = mContext;
this.listImages = getImages();
}
private List<Integer> getImages() {
List<Integer> results = new ArrayList<>();
results.add(R.drawable.outline1);
results.add(R.drawable.outline2);
results.add(R.drawable.outline3);
results.add(R.drawable.outline4);
results.add(R.drawable.outline5);
results.add(R.drawable.outline6);
results.add(R.drawable.outline7);
results.add(R.drawable.outline8);
results.add(R.drawable.outline9);
results.add(R.drawable.outline10);
return results;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_images,parent,false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
holder.imageView.setImageResource( listImages.get(position));
holder.setImageOnC(new ImageOnC() {
#Override
public void onClick(int position) {
Common.PICTURE_SELECTED = listImages.get(position);
mContext.startActivity(new Intent(mContext, Colorful.class));
}
});
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position, List<Object>payload){
//if so, then the progress bar only works for the first image in recyclerview
if(!payload.isEmpty()){
if(payload.get(position) instanceof Integer)
holder.progressBar.setVisibility(View.GONE);
}
else super.onBindViewHolder(holder, position, payload);
}
#Override
public int getItemCount() {
return listImages.size();
}
}
I add this to activity
private void initView() {
recyclerView = findViewById(R.id.recycle_view_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adabter = new ImageAdabter(this);
recyclerView.setAdapter(adabter);
}
#Override
public void onResume() {
super.onResume();
if (adabter != null) {
adabter.notifyItemChanged(position, position);
}
}
in xml file use Progress bar visibility gone

How to call an Interstitial by clicking on an item in the list that goes through an Adapter?

I need to call an Interstitial in this Activity by clicking on an item in the list that comes from my Adapter.
public class SoundRecyclerAdapter extends RecyclerView.Adapter<SoundRecyclerAdapter.SoundViewHolder> {
private final ArrayList<SoundObject> soundObjects;
SoundRecyclerAdapter(ArrayList<SoundObject> soundObjects) {
this.soundObjects = soundObjects;
}
#NonNull
#Override
public SoundViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.sound_item, parent, false);
return new SoundViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull SoundViewHolder holder, int position) {
final SoundObject object = soundObjects.get(position);
final Integer soundID = object.getItemID();
holder.itemTextView.setText(object.getItemName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I tried calling the interstitial here, but to no avail
EventHandlerClass.startMediaPlayer(v, soundID);
}
});
// Handle actions when the user presses a sound button
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
EventHandlerClass.popupManager(v, object);
return true;
}
});
}
#Override
public int getItemCount() {
return soundObjects.size();
}
class SoundViewHolder extends RecyclerView.ViewHolder {
final TextView itemTextView;
SoundViewHolder(View itemView) {
super(itemView);
itemTextView = itemView.findViewById(R.id.textViewItem);
}
}
}
Pass context as parameter of adapter's constructor:
private Context context;
SoundRecyclerAdapter(Context context, ArrayList<SoundObject> soundObjects) {
this.soundObjects = soundObjects;
this.context = context;
}
and use it in click handler
Use this code in the setOnClickListener() method:
mInterstitialAd = new InterstitialAd(SoundRecyclerAdapter.this);
Then add the adrequests and load the ad.

RecyclerView Item Click Listener the Right Way

I use RecyclerView adapter to display data inside an activity, I want to implement onClickListener inside the activity, currently, I am setting onClickListener inside adapter as usual which works fine.
public void onBindViewHolder(MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vname.setText(data.getName());
holder.vname.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, "clicked on " +position, Toast.LENGTH_SHORT).show();
}
});
}
However I want to implement it inside activity so I have greater control. This doesn't serve my purpose. I think it'll be useful for a lot of us.
You need to check this tutorial here for better understanding on how you can achieve the behaviour that you want.
In case of handling the onClickListener from your activity you need to work based on a callback implementation with an interface. Pass the interface from the activity to your adapter and then call the callback function from your adapter when some items are clicked.
Here's a sample implementation from the tutorial.
Let us first have the interface.
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
You need to modify your adapter to take the listener as the parameter like the one stated below.
private final List<ContentItem> items;
private final OnItemClickListener listener;
public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) {
this.items = items;
this.listener = listener;
}
Now in your onBindViewHolder method, set the click listener.
#Override public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), listener);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
...
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
Now setting the adapter in your RecyclerView.
recycler.setAdapter(new ContentAdapter(items, new ContentAdapter.OnItemClickListener() {
#Override public void onItemClick(ContentItem item) {
Toast.makeText(getContext(), "Item Clicked", Toast.LENGTH_LONG).show();
}
}));
So the whole adapter code looks like the following.
public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
private final List<ContentItem> items;
private final OnItemClickListener listener;
public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) {
this.items = items;
this.listener = listener;
}
#Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item, parent, false);
return new ViewHolder(v);
}
#Override public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), listener);
}
#Override public int getItemCount() {
return items.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
name.setText(item.name);
Picasso.with(itemView.getContext()).load(item.imageUrl).into(image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
Registering clickListener inside onCreateViewHolder instead of onBindViewHolder is more performant since you only add listener when a view is created not ever time recyclerView is scrolled.
And i use ListAdapter with DiffUtil callback instead of RecyclerViewAdapter
abstract class BaseListAdapter<ItemType>(
callBack: DiffUtil.ItemCallback<ItemType> = DefaultItemDiffCallback(),
private inline val onItemClicked: ((ItemType, Int) -> Unit)? = null
) : ListAdapter<ItemType, BaseItemViewHolder>(
AsyncDifferConfig.Builder<ItemType>(callBack)
.setBackgroundThreadExecutor(Executors.newSingleThreadExecutor())
.build()
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseItemViewHolder {
return BaseItemViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
getLayoutRes(viewType),
parent, false
)
).apply {
onViewHolderCreated(this, viewType, binding)
}
}
fun createCustomViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return BaseItemViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
getLayoutRes(viewType),
parent, false
)
)
}
override fun onBindViewHolder(
holder: BaseItemViewHolder,
position: Int,
payloads: MutableList<Any>
) {
val item: ItemType? = currentList.getOrNull(position)
item?.let {
holder.binding.setVariable(BR.item, item)
onViewHolderBound(holder.binding, item, position, payloads)
holder.binding.executePendingBindings()
}
}
override fun onBindViewHolder(holder: BaseItemViewHolder, position: Int) {
}
/**
* get layout res based on view type
*/
protected abstract fun getLayoutRes(viewType: Int): Int
/**
* Called when a ViewHolder is created. ViewHolder is either created first time or
* when data is refreshed.
*
* This method is not called when RecyclerView is being scrolled
*/
open fun onViewHolderCreated(
viewHolder: RecyclerView.ViewHolder,
viewType: Int,
binding: ViewDataBinding
) {
binding.root.setOnClickListener {
onItemClicked?.invoke(getItem(viewHolder.bindingAdapterPosition), viewHolder.bindingAdapterPosition)
}
}
/**
* bind view while RecyclerView is being scrolled and new items are bound
*/
open fun onViewHolderBound(
binding: ViewDataBinding,
item: ItemType,
position: Int,
payloads: MutableList<Any>
) {
}
}
open class BaseItemViewHolder(
val binding: ViewDataBinding
) : RecyclerView.ViewHolder(binding.root)
class DefaultItemDiffCallback<ItemType> : DiffUtil.ItemCallback<ItemType>() {
override fun areItemsTheSame(
oldItem: ItemType,
newItem: ItemType
): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(
oldItem: ItemType,
newItem: ItemType
): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
}
Another better user experience is using onBindViewHolder with payLoad which lets you only update some part of the rows instead of whole row. For instance you have image, title and body in rows, and only body changes frequently, without payload image flashes and provides bad user experience. But with payload you can decide which part of the row should be updated allowing you not to reload parts that were not updated.
very simple and clean solution is:
create a class with the name of RecyclerTouchListener:
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
in your recyclerview activity:
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
speech(countries_list_code[position]);
}
#Override
public void onLongClick(View view, int position) {
}
}));
I found super duper easy method! I recommend this one
Example Code:
public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
private final List<ContentItem> items;
private final OnItemClickListener listener;
public ContentAdapter(List<ContentItem> items, OnItemClickListener listener) {
this.items = items;
this.listener = listener;
}
#Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item, parent, false);
return new ViewHolder(v);
}
#Override public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), listener);
}
#Override public int getItemCount() {
return items.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView name;
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
image = (ImageView) itemView.findViewById(R.id.image);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
name.setText(item.name);
Picasso.with(itemView.getContext()).load(item.imageUrl).into(image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}
And Use RecyclerView Adapter using below code:
recycler.setAdapter(new ContentAdapter(items, new ContentAdapter.OnItemClickListener() {
#Override public void onItemClick(ContentItem item) {
Toast.makeText(getContext(), "Item Clicked", Toast.LENGTH_LONG).show();
}
}));
i found this from here
Hope it helped you.
In my way, I just created a single instance of ClickListener, And it dispatches click event to both RecyclerView and Activity or Fragment:
class LeagueAdapter(
onLeagueSelected: (League, Int, View) -> Unit
) : RecyclerView.Adapter<LeagueHolder>() {
private val dataSet = arrayListOf<League>()
private val clickListener = View.OnClickListener { view ->
val adapterPosition = view.tag as Int
onLeagueSelected(dataSet[adapterPosition], adapterPosition, view)
// perform adapter related action here ...
}
override fun getItemCount(): Int {
return dataSet.size
}
override fun onBindViewHolder(holder: LeagueHolder, position: Int) {
// put item position in tag field
holder.itemView.tag = position
holder.itemView.setOnClickListener(clickListener)
}
}
And inside Activity, we have something like this:
private val headerAdapter = LeagueAdapter { league, i, view ->
Log.e(TAG, "item clicked $i")
}
Create an interface for the adapter class
private OnItemClickListener mListener;
public CustomAdapter(List<Listdata> listdata, OnItemClickListener listener) {
mListener = listener;
...
...
}
private class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ViewHolder(View view) {
...
...
view.setOnClickLister(this);
}
#override
public void onClick(View v) {
mListener.onAdapterItemClick(getAdapterPosition())
}
}
interface OnItemClickListener {
void onAdapterItemClick(int position);
}
Let the activity implement the interface
public class CustomListActivity extends AppCompatActivity implements OnItemClickListener {
...
...
#override
public void onAdapterItemClick(int position) {
Toast.makeText(activity, "clicked on " +position, Toast.LENGTH_SHORT).show();
}
There is another way of doing this, check out this implementation
You can let your Activity implements View.OnClickListener and pass it to adapter. Below is an example.
class RAdapter extends RecyclerView.Adapter<>{
View.OnClickListener listner;
public RAdapter(View.OnClickListener listner) {
this.listner = listner;
}
public void onBindViewHolder(MyHolder holder, final int position) {
holder.vname.setOnClickListener(listner);
}
}
But to handle click in Activity you will going to need clicked position. You can have it with adapter.getAdapterPosition() to validate which item is clicked.
Apart from that To pass click event to the Fragment/Activity you can use a Custom callback listener this way your Adapter will be reusable .
A better way to handle clicks in ViewHolder. See the below example.
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
Button button;
public Holder(View itemView) {
super(itemView);
button=itemView.findViewById(R.id.b1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.b1){
int position=getAdapterPosition();
// Call the call method here
// with position or data Object itself
}
}
}
If I understood correctly you want to set the on click logic in the Activity.
You can do this by setting the OnClickListener in the Activity and passing it in the Adapter constructor.
MyAdapter myAdapter = new MyAdapter(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, "clicked on " +position, Toast.LENGTH_SHORT).show();
}
}));
And your MyAdapter Constructor would be:
final private OnClickListener onClickListener;
public MyAdapter(OnClickListener onClickListener) {
this.OnClickListener = OnClickListener;
}
So your new code would be something like this
public void onBindViewHolder(MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vname.setText(data.getName());
holder.vname.setOnClickListener(onClickListener);
}
RecyclerView widget only has 2 useful listeners for this scenario:
RecyclerView.OnChildAttachStateChangeListener - covered here
RecyclerView.OnItemTouchListener - the one that I will be covering
the code is inspired by TouchEvents sample related to Accessibility, and works in Activity/Fragment without setting any listeners in the Adapter
recyclerView.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
var downTouch = false
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
when (e.action) {
MotionEvent.ACTION_DOWN -> downTouch = true
MotionEvent.ACTION_UP -> if (downTouch) {
downTouch = false
recyclerView.findChildViewUnder(e.x, e.y)?.let {
val position = rv.getChildAdapterPosition(it)
Toast.makeText(rv.context, "clicked on $position", Toast.LENGTH_SHORT)
.show()
}
}
else -> downTouch = false
}
return super.onInterceptTouchEvent(rv, e)
}
})
There's another very simple way documented in CodePath.
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(
new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do stuff
}
}
);
The implementation of ItemClickSupport.
Personally, I like to handle this via RxJava subjects:
A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by re-emitting them, and it can also emit new items.
For more info read Understanding RxJava Subject — Publish, Replay, Behavior and Async Subject.
in Adapter:
public static PublishSubject<MyData> onClickSubject = PublishSubject.create();
ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
.
.
.
#Override
public void onClick(View view) {
onClickSubject.onNext(getItem(getAdapterPosition()));
}
}
Add your disposables to a CompositeDisposable and dispose them in onDestroy():
private CompositeDisposable compositeDisposable = new CompositeDisposable();
in onCreate():
compositeDisposable.add(MyAdapter.onClickSubject.subscribe(myData -> {
//do something here
}));
in onDestroy():
compositeDisposable.dispose();
Note:
1. getItem() is a method of androidx.recyclerview.widget.ListAdapter and androidx.paging.PagedListAdapter if you are extending RecyclerView.Adapter you can get item from your data list by position.
2. to use Disposables you need RxJava2 or above
Kotlin
I'd better to add item click in onCreateViewHolder like this
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int):
ProductViewHolder {
val view: View = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.layout_product_item, viewGroup, false)
return ProductViewHolder(view).also { viewHolder ->
viewHolder.itemView.setOnClickListener {
val position = viewHolder.layoutPosition
if (position != RecyclerView.NO_POSITION) {
// do what you want with data[position]
}
}
}
}
You can implement the View.OnClickListener interface in your RecyclerView.ViewHolder class and call it from there.
In your Adapter class create a public interface.
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
private OnItemClickListener onItemClickListener;
On your ViewHolder class, you can implement the View.OnClickListener interface and set an onclick listener to the itemView.
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView myText;
public WalletViewHolder(#NonNull View itemView) {
super(itemView);
myText= itemView.findViewById(R.id.my_text_view);
// Set click listener for each item view
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(getAdapterPosition());
}
}
}
Then your OnItemClickListener will be created only once.
I always have one Generic Adapter in my project to avoid make a Adapter class every I use a Recyclerview. Here some example
public class AdapterRecyclerviewTextOnly extends RecyclerView.Adapter<AdapterRecyclerviewTextOnly.ViewHolder> {
private RecyclerView recyclerView;
private OnRecyclerviewListener onRecyclerviewListener;
public interface OnRecyclerviewListener {
void onRecyclerviewBind(RecyclerView recyclerView, AdapterRecyclerviewTextOnly.ViewHolder viewHolder, int position);
void onRecyclerviewClick(RecyclerView recyclerView, int position);
int onItemCount(RecyclerView recyclerView);
}
public void setOnRecyclerviewListener(OnRecyclerviewListener listener) { this.onRecyclerviewListener = listener; }
public AdapterRecyclerviewTextOnly(RecyclerView recyclerView) {
super();
this.recyclerView = recyclerView;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
RecyclerView recyclerView;
public TextView textView;
ViewHolder(RecyclerView recyclerView, View itemView) {
super(itemView);
this.recyclerView = recyclerView;
this.itemView.setOnClickListener(this);
this.textView = itemView.findViewById(R.id.textview_title);
}
void onBind(int position) { onRecyclerviewListener.onRecyclerviewBind(this.recyclerView, this, position); }
#Override
public void onClick(View v) {
onRecyclerviewListener.onRecyclerviewClick(this.recyclerView, getAdapterPosition());
}
}
#Override
public AdapterRecyclerviewTextOnly.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview_text_only, parent, false);
return new ViewHolder(this.recyclerView, inflatedView);
}
#Override
public void onBindViewHolder(AdapterRecyclerviewTextOnly.ViewHolder holder, int position) {
holder.onBind(position);
}
#Override
public int getItemCount() {
return onRecyclerviewListener.onItemCount(this.recyclerView);
}
}
And then in your Activity Class, you can use this adapter with :
this.recyclerView = findViewById(R.id.recyclerview);
this.recyclerView.setHasFixedSize(true);
this.recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
AdapterRecyclerviewTextOnly recyclerViewAdapter = new AdapterRecyclerviewTextOnly(this.recyclerView);
this.recyclerView.setAdapter(this.recyclerViewAdapter);
this.recyclerViewAdapter.setOnRecyclerviewListener(new AdapterRecyclerviewTextOnly.OnRecyclerviewListener() {
#Override
public void onRecyclerviewBind(RecyclerView recyclerView, AdapterRecyclerviewTextOnly.ViewHolder viewHolder, int position) {
}
#Override
public void onRecyclerviewClick(RecyclerView recyclerView, int position) {
}
#Override
public int onItemCount(RecyclerView recyclerView) {
}
});
You can reuse this with 2 or 3 recyclerview too.
First, declare a globar listener private AdapterRecyclerviewTextOnly.OnRecyclerviewListener listener;.
Then init the listener with new object then set the your every recyclerview with the listener. Use specific identifier:
if (recyclerView == recyclerViewA){ } else if (recyclerView == recyclerViewB) { } to manage your recyclerview inside the adapter.

Categories