Wanjala Alex
Wanjala Alex

Reputation: 141

Call method inside adapter Class

I have a method Called addItem() inside an Adapter I want to call it from MainAcivity .

public class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final int VIEW_TYPE_FIRST = 0;
private static final int VIEW_TYPE_SECOND = 1;

List<Message> mList;
Context context;
LayoutInflater inflater;

public MessageAdapter(Context context, List<Message> mList) {
    this.context = context;
    this.mList = mList;
    this.inflater = LayoutInflater.from(context);
}


public void addItem(Message item) {
    mList.add(mList.size()+1,item);
    notifyItemInserted(mList.size()+1);

}

Upvotes: 0

Views: 1396

Answers (2)

Rajesh
Rajesh

Reputation: 2618

// Adapter initialization
MessageAdapter adapter = new MessageAdapter(MainActivity.this, list);
recyclerview.setAdapter(adapter); // setting your adapter
adapter.addItem(your model); // Call method using an object of adapter;

Note: every non static method can be access only by object of that class after Initialization.

Upvotes: 3

HelloSadness
HelloSadness

Reputation: 955

Well in your Activity, you will have your adapter object.
Just call yourAdapter.addItem(yourMessage);

Upvotes: 1

Related Questions