如何从oncreateview中的另一个函数获取数据?

0ejtzxu1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(321)

我已从名为itemdetails的活动发送数据:

  1. private void AddToCart(String name, String price) {
  2. OrdersFragment fragment = new OrdersFragment();
  3. fragment.receiveData(name, price);
  4. }

我想在ordersfragment中显示回收器视图中的数据(列表为空,当我获得订单时,它将被传递的数据填充)
所以我在这里得到数据:

  1. public void receiveData(String name, String price) {
  2. this.name = name;
  3. this.price = price;
  4. }

但我无法在oncreateview中访问它:

  1. public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
  2. @Nullable Bundle savedInstanceState) {
  3. View view = inflater.inflate(R.layout.fragment_rv_orders, container, false);
  4. txt_name = view.findViewById(R.id.order_item_name);
  5. txt_price = view.findViewById(R.id.order_item_price);
  6. txt_name.setText(name);
  7. txt_price.setText(price);
  8. return view;
  9. }

我尝试了各种方法将数据从活动发送到片段,这是它实际将数据发送到片段的唯一方法,我只是不知道如何访问它。欢迎任何建议。

h9vpoimq

h9vpoimq1#

您应该在 receiveData 片段的方法。在片段中声明两个全局变量(我假设它们是 TextView )

  1. private TextView txt_name;
  2. private TextView txt_price;

并在 onCreateView 方法:

  1. public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
  2. @Nullable Bundle savedInstanceState) {
  3. View view = inflater.inflate(R.layout.fragment_rv_orders, container, false);
  4. txt_name = view.findViewById(R.id.order_item_name);
  5. txt_price = view.findViewById(R.id.order_item_price);
  6. return view;
  7. }

最后,使用

  1. public void receiveData(String name, String price) {
  2. txt_name.setText(name);
  3. txt_price.setText(price);
  4. }

我听说你指的是 RecyclerView 在您的问题中,如果您需要填充该类型的列表,那么您需要在片段中创建一个适配器并在 receiveData 方法。

展开查看全部

相关问题