我使用View寻呼机在我的应用程序中显示滑动图像。代码工作得很好但是当用户导航到其他片段时,当返回到前一个片段时,图像不会显示。视图寻呼机中的图像仅为应用程序启动时显示,否则无法显示。
代码
public class HomeScreen extends BaseFragment {
ViewPager viewPager;
Fragment fragment;
private int[] images = {R.drawable.ic_launcher, R.drawable.nav_bg};
private FragmentManager fragmentManager;
private Timer swipeTimer;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_screen, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
fragmentManager = getFragmentManager();
viewPager.setAdapter(new pagerAdapter(fragmentManager, images));
final Handler handler = new Handler();
final Runnable update = new Runnable() {
@Override
public void run() {
for (int i = 0; i < images.length; i++) {
viewPager.setCurrentItem(i);
}
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(update);
}
}, 1000, 5000);
}
public class pagerAdapter extends FragmentStatePagerAdapter {
private int[] images;
public pagerAdapter(FragmentManager fm, int[] images) {
super(fm);
this.images = images;
}
@Override
public Fragment getItem(int i) {
fragment = ImageSwitcher.newInstance(images[i]);
return fragment;
}
@Override
public int getCount() {
return images.length;
}
}
}
片段代码
public class ImageSwitcher extends BaseFragment {
private ImageView imageView;
public static final ImageSwitcher newInstance(int image) {
ImageSwitcher imageSwitcher = new ImageSwitcher();
Bundle bundle = new Bundle();
bundle.putInt("image", image);
imageSwitcher.setArguments(bundle);
return imageSwitcher;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
}
private void initialize() {
imageView = (ImageView) view.findViewById(R.id.image_switcher);
imageView.setBackgroundResource(getArguments().getInt("image"));
}
}
答案 0 :(得分:0)
更改
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
return view;
}
到
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
initialize();
return view;
}