Gray out fragment in background

孤者浪人 提交于 2019-12-04 21:02:46

Just put a View in between the Fragments so that it overlays the Fragment you want to gray out. Then set the background to be completely black and the alpha to 0 and visibility to GONE.

When you finally want to gray out the other Fragment set the visibility to VISIBLE and set the alpha to some value you like, maybe 0.5 or something like that. I mostly tend to animate the alpha value to get a nice effect.


So your layout should look something like this:

<FrameLayout
    android:id="@+id/fragmentContainerOne"
    android:layout_width="match_parent"
    android:layout_height="match_parent" /> 

<View
    android:id="@+id/fadeBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layerType="hardware"
    android:alpha="0"
    android:visibility="gone"
    android:background="@android:color/black"/>

<FrameLayout
    android:id="@+id/fragmentContainerTwo"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

The Fragment in the upper FrameLayout will be the one that is grayed out and you would do that like this:

final View fadeBackground = findViewById(R.id.fadeBackground);
fadeBackground.setVisibility(VISIBLE);
fadeBackground.animate().alpha(0.5f); // The higher the alpha value the more it will be grayed out

When you want to remove that effect again you would do it like this:

fadeBackground.animate().alpha(0.0f).setListener(new Animator.AnimatorListener() {
    @Override
    public void onAnimationStart(Animator animation) {

    }

    @Override
    public void onAnimationEnd(Animator animation) {
        // As soon as the animation is finished we set the visiblity again back to GONE
        fadeBackground.setVisibility(View.GONE);
    }

    @Override
    public void onAnimationCancel(Animator animation) {

    }

    @Override
    public void onAnimationRepeat(Animator animation) {

    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!