如何 select 来自 recyclerview 的人并将其发送到 activity

How to select a person from recyclerview and send it to the activity

我正在开发一个控制任务的应用程序。我必须从列表中选择一个人作为任务的处理者。我制作了一个 TextView,单击它会打开一个包含 recyclerview 的 DialogFragment。我如何从 recyclerView select 一个人并将其发送回 activity。我尝试过使用界面,但还没有成功。

下面是 DialogFragment 和 MainActivity:

AlertDialogFragment

RecyclerView recyclerViewPersons;
List<PERSON> personList = new ArrayList<>();
PersonsAdapter personsAdapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.dialog_persons_list, container);


    recyclerViewPersons = v.findViewById(R.id.recyclerViewPersons);


    recyclerViewPersons.setLayoutManager(new  LinearLayoutManager(this.getActivity()));
    personsAdapter = new PersonsAdapter(getActivity());
    personsAdapter.setData(personList);
    recyclerViewPersons.setAdapter(personsAdapter);

    return v;
}


public void setAdapterData(List<PERSON> personList) {
    this.personList = personList;
}

}

MainActivity

PersonsAdapter personsAdapter;
final FragmentManager fragmentManager = getSupportFragmentManager();
final AlertDialogFragment alertDialogFragment = new AlertDialogFragment();

protected void onCreate(Bundle savedInstanceState) {

txtPersons.setOnClickListener(v -> {

        alertDialogFragment.setAdapterData(personList);
        alertDialogFragment.show(fragmentManager, "dialog recycler");


    });

}

首先在Fragment中定义一个接口(发送Person数据)并让它在Activity中实现。

然后在Recycler Adapter中再定义一个接口,让其在Fragment中实现。这个界面会在点击 Recycler item 后获取信息。在 Adapter 的布局中点击调用此接口。

然后最后无论你在片段中得到什么数据,通过第一个接口将它传回给activity。 希望这有帮助吗?

您说您成功地将数据从 Adapter 发送到 DialogFragment。现在您可以将此数据从 DialogFragment 发送到 Activity。

为此,您可以在 DialogFragment 内部或外部创建另一个界面。然后你可以用 activity 实现这个片段并用它的主体覆盖这个接口。

现在,在 DialogFragment 中覆盖 onAttach 方法并实例化此接口实例。

界面

public interface OnMyInterface {
    public void onMyData(your data);
}

DialogFragment

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());
   }
}

Activity

public class MyActivity implements OnMyInterface {
    @Override
    public void onMyData(your data) {
        //get this data
    }
}

或者您也可以试试这个方法: https://camposha.info/source/android-data-passing-fragment-activity-via-intent