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

问题描述 投票:0回答:2

我正在开发一个控制任务的应用程序。我必须从列表中选择一个人作为任务的处理程序。我创建了一个TextView,当单击时打开一个包含recyclerview的DialogFragment。如何从recyclerView中选择一个人并将其发送回活动。我尝试使用接口,但还没有工作。

下面是DialogFragment和MainActivity:

警报对话框片段

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

}

我的知识

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");


    });

}

android android-fragments android-recyclerview dialog click
2个回答
0
投票

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

然后,在Recycler Adapter中再定义一个接口并让它在Fragment中实现。单击Recycler项后,此界面将获取信息。单击时在Adapter的布局中调用此接口。

最后,无论你在片段中获得什么数据,都可以通过第一个接口将其传回活动。希望这可以帮助?


1
投票

您说您设法将数据从Adapter发送到DialogFragment。现在,您可以将此数据从DialogFragment发送到Activity。

为此,您可以在DialogFragment内部或外部创建另一个界面。然后,您可以使用活动实现此片段,并使用其主体覆盖此接口。

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

活动

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

© www.soinside.com 2019 - 2024. All rights reserved.