简体   繁体   中英

How to make Fragment background transparent?

I'm using Android Navigation Components with nav_graph and I want to make background of all fragments transparent. I tried to use the code from following resource: click For activity it's working fine, but in fragment background is always white.

public class SettingsFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

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

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackground(new ColorDrawable(Color.TRANSPARENT));
    }
}

The easiest way to solve this is to set the transparency of the Fragment in the XML.

You can define a transparent color in colors.xml like this: <color name="transparent">#00000000</color>

and then reference it in your fragment.xml like this: android:backgroundTint="@color/transparent"

Additionally its advisable, to set View-Altering commands into the onCreate() .

Also you can define an android:alpha="0" attribute in the .xml to test if that will set the background color to transparent. But I guess this will only change the opacity of the whole fragment including child elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM