Android 如何从recyclerview中选择一个人并将其发送到活动

Android 如何从recyclerview中选择一个人并将其发送到活动,android,android-fragments,android-recyclerview,dialog,click,Android,Android Fragments,Android Recyclerview,Dialog,Click,我正在开发一个控制任务的应用程序。我必须从列表中选择一个人作为任务的处理者。我制作了一个文本视图,当点击时会打开一个包含recyclerview的DialogFragment。如何从recyclerView中选择一个人并将其发送回活动。我尝试过使用接口,但还没有成功 以下是DialogFragment和主要活动: AlertDialogFragment }首先在片段中定义一个接口(用于发送个人数据),并让它在活动中实现 然后,在Recycler Adapter中再定义一个接口&让它在片段中实现。

我正在开发一个控制任务的应用程序。我必须从列表中选择一个人作为任务的处理者。我制作了一个文本视图,当点击时会打开一个包含recyclerview的DialogFragment。如何从recyclerView中选择一个人并将其发送回活动。我尝试过使用接口,但还没有成功

以下是DialogFragment和主要活动:

AlertDialogFragment

}

首先在片段中定义一个接口(用于发送个人数据),并让它在活动中实现

然后,在Recycler Adapter中再定义一个接口&让它在片段中实现。此界面将在单击回收项目后获取信息。单击时在适配器的布局中调用此接口

最后,无论您在片段中获得什么数据,都要通过第一个接口将其传递回activity。
希望这有帮助吗?

您说过您设法将数据从适配器发送到DialogFragment。现在您可以将此数据从DialogFragment发送到Activity

为此,您可以在DialogFragment内部或外部创建另一个接口。然后您可以用活动实现这个片段,并用它的主体重写这个接口

现在,在DialogFragment内部重写onAttach方法并实例化这个inferface实例

接口

public interface OnMyInterface {
    public void onMyData(your data);
}
对话框片段

private OnMyInterface onMyInterface;

public ForgotAndResetPasswordFragment() {}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_your_layout, container, false);
}

@Override
public View onViewCreated(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //send the data to activity using on onMyInterface
    onMyInterface.onMyData(your data);
}

@Override
public void onAttach(@NonNull Context context) {
   super.onAttach(context);

   try {
      onMyInterface = (OnMyInterface) context;

   } catch (ClassCastException e) {
      throw new ClassCastException(context.toString());
   }
}
活动

public class MyActivity implements OnMyInterface {
    @Override
    public void onMyData(your data) {
        //get this data
    }
}
或者您也可以尝试这种方法:

我设法将数据从适配器发送到DialogFragment,但实际上无法将其发送到活动。从DialogFragment向Activity发送数据有什么诀窍吗?
private OnMyInterface onMyInterface;

public ForgotAndResetPasswordFragment() {}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_your_layout, container, false);
}

@Override
public View onViewCreated(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //send the data to activity using on onMyInterface
    onMyInterface.onMyData(your data);
}

@Override
public void onAttach(@NonNull Context context) {
   super.onAttach(context);

   try {
      onMyInterface = (OnMyInterface) context;

   } catch (ClassCastException e) {
      throw new ClassCastException(context.toString());
   }
}
public class MyActivity implements OnMyInterface {
    @Override
    public void onMyData(your data) {
        //get this data
    }
}