java - 如何从 onCreateView 中的另一个函数获取数据?
问题描述
我从一个名为 ItemDetails 的活动中发送了数据:
private void AddToCart(String name, String price) {
OrdersFragment fragment = new OrdersFragment();
fragment.receiveData(name, price);
}
当我得到它时,我想在 OrdersFragment 的回收器视图中显示数据(列表是空的,它将被传递的数据填充,因为我得到了订单)
所以我在这里得到数据:
public void receiveData(String name, String price) {
this.name = name;
this.price = price;
}
但我无法在 onCreateView 中访问它:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rv_orders, container, false);
txt_name = view.findViewById(R.id.order_item_name);
txt_price = view.findViewById(R.id.order_item_price);
txt_name.setText(name);
txt_price.setText(price);
return view;
}
我尝试了各种将数据从活动发送到片段的方法,这是它实际将数据发送到片段的唯一方法,我只是不知道如何访问它。欢迎任何建议。
解决方案
您应该receiveData
在片段的方法中设置字符串值。在片段中声明两个全局变量(我假设它们是TextView
)
private TextView txt_name;
private TextView txt_price;
并在方法中初始化它们onCreateView
:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rv_orders, container, false);
txt_name = view.findViewById(R.id.order_item_name);
txt_price = view.findViewById(R.id.order_item_price);
return view;
}
最后,设置文本值
public void receiveData(String name, String price) {
txt_name.setText(name);
txt_price.setText(price);
}
我读到您RecyclerView
在问题中指的是 a ,如果您需要填充该类型的列表,则需要在 Fragment 中创建一个 Adapter 并将其填充到receiveData
方法中。
推荐阅读
- node.js - Inversify - Nodejs- 容器绑定导致超出最大调用大小
- jsp - 如何检查对 index.ftl 的 HTTP 请求?
- python - 是否可以在 Pandas.ReadSQL 中使用“chunksize=”选项来限制/限制内存/RAM 的使用?
- reactjs - rc-滑块图标或 html 标签
- python - 我在 python 3.6 中安装 webdrive 模块时遇到问题
- algorithm - 对于允许重叠的覆盖问题,是否有众所周知或有效的算法?
- typo3 - 有没有办法在typo3中可见的前端添加记录更改成为历史?
- c++ - 如何对对象进行异步销毁并立即分配一个新对象
- c# - 将数据从主页上的 web api 传递到 xamarin 表单中的详细信息页面
- string - 在打字稿中连接字符串时如何匹配字符串文字类型