作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何将数据从 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/
我是一名优秀的程序员,十分优秀!