如何从适配器Android调用片段中的方法

Eva*_*ana 3 java android android-fragments

我需要帮助所以我有一个片段,它有一个recycleView,在recycleView里面有一个按钮.

单击后按钮必须打开已经在基本片段中声明的对话框,所以我只调用"openDialog(DIALOG_CHECK);"

现在我如何在我的适配器上调用该对话框我已经在片段中创建了一个方法并从适配器调用它并发出错误"Java lang null pointer"

这是我的代码:

DeliveryFragment delivFrag = new DeliveryFragment();
holder.editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delivFrag.doEdit();
            }
        });
Run Code Online (Sandbox Code Playgroud)

在片段中

public  void doEdit(){
        openDialog(DIALOG_EDIT_ITEM);
    }
Run Code Online (Sandbox Code Playgroud)

小智 10

更新您的适配器构造函数以接受 Fragment 作为参数。

customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1, getList, HomeFragment.this);
Run Code Online (Sandbox Code Playgroud)

适配器类:

public CustomAdapter(Context context, int id, HomeFragment fragment) {
    this.fragment = fragment;
}
Run Code Online (Sandbox Code Playgroud)

调用适配器:

((FragmentName)fragment).methodName();
Run Code Online (Sandbox Code Playgroud)


hus*_*yin 8

只是一个更好理解的简单例子.使用界面.

public class TestAdapter extends RecyclerView.Adapter<TestAdapter.ViewHolder> {    
  private static OnItemClickListener mOnItemClickLister;

  public interface OnItemClickListener {
    void onItemClicked(View view, int pos);
  }

  public void setOnItemClickListener(OnItemClickListener listener) {    
    mOnItemClickLister = listener;
  }

  public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {    
    Button mBtnTest;
    Context mContext;

    //We also create a constructor that accepts the entire item row
    //and does the view lookups to find each subview.
    public ViewHolder(Context context, View itemView) {    
      //Stores the itemView in a public final member variable that can be used
      //to access the context from any ViewHolder Instance
      super(itemView);    
      mContext = context;
      mBtnTest = (Button) itemView.findViewById(R.id.message_button);
      itemView.setOnClickListener(this);
    }

    @Override public void onClick(View v) {
      int position = v.getLayoutDirection();
      mOnItemClickLister.onItemClicked(v, position);
    }
  }
}   
Run Code Online (Sandbox Code Playgroud)

片段部分

class FragmentTest extends Fragment implements OnItemClickListener {    
  TestAdapter adapter = new TestAdapter(); //you can initialize according to  your logic

  //set the fragment as a listener to adapter
  this.adapter.setOnItemClickListener(onItemClickListener);

  public void onItemClicked(View view, int pos) {
    //do whatever you want here...
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

您必须在 Adapter 类中编写一个接口,并在调用适配器的片段中实现该功能。

这是带有项目单击操作的回收器视图的示例应用程序。检查一次可能对您有用。 https://www.dropbox.com/s/2q1ywnehz454axw/SamplePro_Recycler.zip?dl=0