Search code examples
androidrandomviewflipper

Random views with View Flipper


I am really new with Android Code. I am trying to show a random Image on my Layout. With the Code below the first Image after onCreate is random. But after that the others are in Order. Is there a way to show after every View a random other view ?

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {


        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

            mViewFlipper = (ViewFlipper) rootView.findViewById(R.id.view_flipper);
            mViewFlipper.setAutoStart(true);
            mViewFlipper.setFlipInterval(4000);
            Random mRandom = new Random();
            mViewFlipper.setDisplayedChild(mRandom.nextInt(400));
            mViewFlipper.startFlipping();


Solution

  • The random image is set only once. After this, the ViewFlipper will not get the next random integer, but will continue from its current position as the interval reaches its end.

    You could use a Handler to issue a new random image after your interval time. This would also take over the handling of flip interval.

    See the accepted answer on ViewFlipper: flipping at random time intervals using random children for example code.

    (Cannot comment yet, so answering in this way)