gpt4 book ai didi

java - 如何将数据从recyclerview适配器传递或发送到fragment

转载 作者:行者123 更新时间:2023-12-02 01:52:00 27 4
gpt4 key购买 nike

如何将数据从 recyclerview 适配器传递到 fragment 以及我必须在 fragment 中编写代码才能接收数据。我已经检查了该网站中的链接,但不幸的是无法获得正确的代码。下面是代码

ExampleAdapter.Java

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item,viewGroup,false);
ExampleViewHolder evh=new ExampleViewHolder(v);
return evh;
}
@Override
public void onBindViewHolder(@NonNull ExampleViewHolder exampleViewHolder, int i) {
final ExampleItem currentItem=mExampleList.get(i);
exampleViewHolder.mTextView.setText(currentItem.getmText());
exampleViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// pass the data to the fragment
}
});
}
@Override
public int getItemCount() {
return mExampleList.size();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ExampleViewHolder(@NonNull View itemView) {
super(itemView);
mTextView=itemView.findViewById(R.id.texttitle);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList){
this.mExampleList=exampleList;
}
}

最佳答案

您可以通过将回调附加到适配器来传递数据:

创建界面:

interface OnTextClickListener {
void onTextClick(ExampleItem data);
}

委托(delegate)回调:

class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {

List<ExampleItem> items;
OnTextClickListener listener;

ExampleAdapter(List<ExampleItem> items, OnTextClickListener listener) {
this.items = items;
this.listener = listener;
}

@Override
public void onBindViewHolder(ExampleViewHolder viewHolder, int position) {
viewHolder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Say you want to pass an ExampleItem back to the fragment...
ExampleItem data = items.get(position);
listener.onTextClick(data);
}
});
}
}

使用接口(interface)实现 fragment :

class YourFragment extends Fragment implements OnTextClickListener {

public onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setAdapter(new ExampleAdapter(this));
}

void onTextClick(ExampleItem data) {
// Now you can do however you want with the data here...
Toast.makeText(getActivity(), "Got: " + data, Toast.LENGTH_SHORT).show()
}
}

关于java - 如何将数据从recyclerview适配器传递或发送到fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52829707/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com