how can I show the snackbar at the bottom of page? I want to show snackbar when clicked on like. I used snackbar in an item of recycleview (crdLayout) so It has been shown at bottom of each item here is the code:
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
itemHolder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar snackbar = Snackbar
.make(itemHolder.crdLayout, "liked", Snackbar.LENGTH_LONG)
snackbar1.show();
}
});
the snackbar each time dont pop up at the bottom of page and instead it comes at bottom of each cardview
In your Snackbar
, you are giving the parameter as itemholder.cardLayout
. So the snackbar will appear below the card layout. You should give the root view of the page to make it appear on the bottom of the page
There are two ways you can achieve this. One is to pass the rootview
in the constructor of the RecyclerViewAdapter
class and pass the argument to the Snackbar
. Another way is to use a callback method in your Activity
or Fragment
class that calls your RecyclerViewAdapter
class.
For the first method, You just pass the rootView
of the page as a constructor parameter and pass the argument in the Snackbar
.
For the second method, You can create an interface in the RecyclerViewAdapter
class, pass the interface instance as a parameter in the constructor, creating a method in the interface and notifying the method when the item has been clicked. Then you can show the Snackbar
in your Activity
class itself. See the code below,
public class YourActivity implements RecyclerViewAdapter.CallbackListener{
View rootView;
@Override
protected void onCreate(Bundle savedInstanceState){
//
rootView = findViewById(R.id.my_root_view);
//
//
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this);
//
//
}
@Override
public void onItemClicked(){
Snackbar snackbar = Snackbar.make(rootView, "liked", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
And your RecyclerViewAdapter class will be,
public class RecyclerViewAdapter {
CallbackListener listener;
public RecyclerViewAdapter (CallbackListener listener){
this.listener = listener;
}
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
itemHolder.like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onItemClicked();
}
});
public interface CallbackListener{
void onItemClicked();
}
}
Though first method is so simple, second method gives you more encapsulation, more cleaner code and more control over code.