适配器类内的调用方法

时间:2017-02-04 09:49:33

标签: android

我在Adapter中调用了addItem()方法,我想从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);

}

2 个答案:

答案 0 :(得分:2)

// 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;
  

注意:初始化后,每个非静态方法只能由该类的对象访问。

答案 1 :(得分:1)

在您的Activity中,您将获得适配器对象 只需调用yourAdapter.addItem(yourMessage);