当我尝试重新加载Fragment时,构造函数的值未更改。例如,如果我打开应用程序,它运行良好,但是当我用Arraylist进行任何更改并尝试重新加载片段时,尽管我通过了列表,但我的ArrayList仍会返回0。
我的活动代码是:
private void setGraphComponent(ArrayList<SpinnerAdapter> weatherSensor, ArrayList<SpinnerAdapter> cattleSensor, ArrayList<SpinnerAdapter> weatherSensor2, ArrayList<SpinnerAdapter> volt, ArrayList<SpinnerAdapter> sign, ArrayList<SpinnerAdapter> vehicleSensor) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
ViewPager graphPager = findViewById(R.id.graphPager);
if (weatherSensor.size() > 1) {
viewPagerAdapter.addFragment(new GraphFragment(this, StaticConfig.SENSOR_1, weatherSensor, 1));
}
}
我的片段代码是:
public GraphFragment(Context context, String title, ArrayList<SpinnerAdapter> adapters, int sensorType) {
this.context = context;
this.title = title;
this.spinnerAdapters = adapters;
this.sensorType = sensorType;
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_fragement, container, false);
TextView textView = view.findViewById(R.id.title);
Spinner devices = view.findViewById(R.id.devices);
init_volleyCallback();
stringVolleyService = new StringVolleyService( stringResult, context);
// Here in spinnerAdapters when I am loading first time its coming 3 count which suppose to be but when I reload it again its coming 0.
setSpinner(spinnerAdapters, devices);
textView.setText(title);
return view;
}
任何建议都会有很大帮助。预先感谢。
答案 0 :(得分:0)
在Android中使用片段时,您不应创建自定义构造函数。你可以
setArguments(Bundle)
将参数传递给片段,然后
稍后使用getArguments()
onAttach(Context)
。这些在 documentation。
在您的情况下,覆盖onAttach(Context)
可能很有意义,因为您获得了一个上下文实例,并且可以确保此是应用程序代码可以在准备使用该片段的地方运行的第一个地方。。
因此在您的片段中实现onAttach
看起来像这样,
@Override
public void onAttach (Context context){
YourActivity activity = (YourActivity) context;
this.title = activity.title; // or activity.getTitle(), you get the idea
this.spinnerAdapters = activity.adapters;
this.sensorType = activity.sensorType;
}