我在Activity中使用TabLayout,FragmentStatePagerAdapter和Fragment,当我运行我的应用程序时,第一个片段没有显示数据,但是当我滚动到第三个片段,然后又滚动到第一个片段时,第一个片段显示数据(第三个片段也显示)。但是我的第二个片段什么也不显示。这是我的适配器:
public class Pager extends FragmentStatePagerAdapter {
int count;
ForecastElements forecastElements;
public Pager(FragmentManager fm, int count, ForecastElements forecastElements) {
super(fm);
this.count = count;
this.forecastElements = forecastElements;
}
@Override
public Fragment getItem(int position) {
Fragment tab = null;
if (position == 0) {
tab = new Tab1();
Bundle bundle = new Bundle();
bundle.putString("name", forecastElements.getName());
bundle.putString("maxTemp1", forecastElements.getMaxTemp1());
tab.setArguments(bundle);
} else if (position == 1) {
tab = new Tab2();
Bundle bundle = new Bundle();
bundle.putString("name", forecastElements.getName());
bundle.putString("maxTemp2", forecastElements.getMaxTemp1());
tab.setArguments(bundle);
} else if (position == 2) {
tab = new Tab3();
Bundle bundle = new Bundle();
bundle.putString("name", forecastElements.getName());
bundle.putString("maxTemp3", forecastElements.getMaxTemp3());
tab.setArguments(bundle);
}
return tab;
}
@Override
public int getCount() {
return count;
}
}
这是我的第二个标签:
public class Tab2 extends Fragment {
private TextView cityName,Maxtemp;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2, container, false);
cityName = (TextView) view.findViewById(R.id.tab2CityName);
Maxtemp = (TextView) view.findViewById(R.id.tab2MaxTemp);
cityName.setText(getArguments().getString("name"));
Maxtemp.setText(getArguments().getString("maxTemp2"));
return view;
}
} 当我运行应用程序时,Tab2为空,但另外两个选项卡正常工作。