Artem Mostyaev
Artem Mostyaev

Reputation: 3908

SurfaceView clears it's contents when detaching

I'm using SurfaceView inside Fragment. When I replace fragment with another one, SurfaceView blinks black for a second and then SurfaceView's fragment is detached.

One popular suggestion is to use setZOrderOnTop(true). But when I use it, SurfaceView simply has the same color as background and doesn't blink. But then it shows over other UI elements and creates more problems.

I noticed that in both cases SurfaceView clears its contents before destroying, so setZOrderOnTop doesn't matter.

Can anybody explain why SurfaceView clears its content when detaching? But another UI elements (Buttons, Lists) don't have such behaviour.

EDIT SurfaceView clears when method onWindowVisibilityChanged of SurfaceView class is called.

Upvotes: 0

Views: 250

Answers (1)

Artem Mostyaev
Artem Mostyaev

Reputation: 3908

I've found a workaround - first add new fragment, then show it and hide old. And then remove old in the async task. The solution is a bit confusing, but I didn't find anything better. In the following example old fragment has tag fragment and the new one fragment2.

FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction().add(R.id.content_frame, fragment, "fragment2").commit();
                fragmentManager.beginTransaction().show(fragment).commit();
                fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("fragment")).commit();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("fragment")).commit();                      
                    }
                }, 1000);

In such method SurfaceView blinks black also, but it is not visible at that moment.

Upvotes: 1

Related Questions