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

How can I get data from another function in onCreateView?

我已经从名为 ItemDetails 的 activity 发送了数据:

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

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

您应该在片段的 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,如果你需要填充该类型的列表,你将需要在片段中创建一个适配器并将其填充到 receiveData方法。