gpt4 book ai didi

android - 如何将 JSON 数据从 Activity 发送到 Fragment?

转载 作者:行者123 更新时间:2023-12-02 16:10:33 25 4
gpt4 key购买 nike

我正在尝试从 JSON 获取数据并将一部分数据发送到所有 fragment 。这是我的代码:

    private void setupViewPager(ViewPager viewPager,ArrayList<Product> productname,int p) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle args = new Bundle();
}
String price = productname.get(1).getPrice();
args.putString("key", price);
TheFragment tf1 = new TheFragment();
TheFragment tf2 = new TheFragment();
TheFragment tf3 = new TheFragment();
TheFragment tf4 = new TheFragment();
adapter.addFragment(tf1 , "ONE");
tf1.setArguments(args);
adapter.addFragment(tf2 , "Two");
tf2.setArguments(args);
adapter.addFragment(tf3 , "Three");
tf3.setArguments(args);
adapter.addFragment(tf4 , "Four");
tf4.setArguments(args);

//3 adapter.addFragment(new TheFragment(), "TWO"); // Can I send data by coding this way?
//3 adapter.addFragment(new TheFragment(), "THREE");
//3 adapter.addFragment(new TheFragment(),"THE 4");
viewPager.setAdapter(adapter);
}

在此之前,我已在数组列表和 n=jsonArray.length(); 中检索了 JSON 值。

setupViewPager(viewPager,arrayList,n);

JSON 文件包含名称、价格和图像。我想在我的 fragment 中显示价格。

public class TheFragment extends Fragment {

TextView tv;
public TheFragment() {

}
String value = getArguments().getString("key");

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* if(value!=null){
tv.setText(value);
} */

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_this, container, false);
tv = (TextView) getView().findViewById(R.id.thePrice);
tv.setText(value);
return view;
}
}

代码未显示任何错误,但应用程序未运行。我犯了哪些错误以及可能的解决方案?谢谢。

最佳答案

更改 fragment 中的这行代码-

   public class TheFragment extends Fragment {

TextView tv;
public TheFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_this, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.thePrice);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String price = getArguments().getString("key");
tv.setText(price);
}
}

希望能顺利进行。

关于android - 如何将 JSON 数据从 Activity 发送到 Fragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com