Search code examples
javaandroidandroid-toast

Displaying toast from a non activity class


I want to display toasts from a non-activity class which is my RecyclerView Adapter.

What can I do to achieve this?

I want to set toasts in the onLoadingStateChanged() switch statements.

I have tried some old codes but they don't seem to work.

I don't want RecylerView Adapter to be in the MainActivity

My Adapter Activity:

public class TalesAdapter extends FirestorePagingAdapter<TalesDetails, TalesAdapter.TalesViewHolder> {

    public TalesAdapter(@NonNull FirestorePagingOptions<TalesDetails> options) {
        super(options);
    }



    @Override
    protected void onBindViewHolder(@NonNull TalesViewHolder holder, int position, @NonNull TalesDetails model) {
        holder.bind(model);

    }

    @NonNull
    @Override
    public TalesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.talesrecyclerview, parent, false);
        return new TalesViewHolder(view);
    }
   

    @Override

    protected void onLoadingStateChanged(@NonNull LoadingState state) {
        switch (state) {
            case LOADING_INITIAL:
            case LOADING_MORE:
             //toast here
                break;

            case LOADED:
             //toast here
            case FINISHED:
             //toast here
                break;

            case ERROR:
             //toast here

                break;
        }

    }

    public class TalesViewHolder extends RecyclerView.ViewHolder  {

        private TextView Title;
        private TextView Matter;
        private TextView Name;

        public TalesViewHolder(View itemView ) {
            super(itemView);
            Name = itemView.findViewById(R.id.tvName);
            Title = itemView.findViewById(R.id.tvTitle);
            Matter = itemView.findViewById(R.id.tvMatter);
        }

        public void bind(TalesDetails tales){
            Name.setText(tales.name);
            Title.setText(tales.title);
            Matter.setText(tales.matter);

        }
    }
}

Solution

  • You have two possibilities :

    1 - Create Context variable

    private Context context;
    
    public TalesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            context = parent.getContext();
    
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.talesrecyclerview, parent, false);
            return new TalesViewHolder(view);
        }
    

    2 - Using implementation 'com.blankj:utilcodex:1.29.0'

    ToastUtils.showShort("YOUR TEXT HERE");