Gray out fragment in background

人走茶凉 提交于 2020-01-13 06:31:26

问题


I have one main Fragment which is in the background when the second Fragment gets called with getFragmentManager().beginTransaction().add. Right now the user can see the main Fragment behind the second Fragment like it should be. But i want it to be like in a grayed look. When the Second Fragment gets called, the main Fragment should gray out. Im not sure what to google (have tried a lot of keywords) to describe this.

My idea was to take a screenshot of the main fragment (bitmap) and make it gray. Is this the right direction?


回答1:


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) {

    }
});


来源:https://stackoverflow.com/questions/26122807/gray-out-fragment-in-background

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