首页 > 解决方案 > 如何从 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;
    }

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

标签: javaandroidandroid-activityandroid-recyclerviewfragment

解决方案


您应该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方法中。


推荐阅读