Home » Android » How to set background color of an fragment to light dark(transparent) programmatically?

How to set background color of an fragment to light dark(transparent) programmatically?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have created a layout programmatically for my fragment.Now I want to set light dark background color to it but how could I do that?
I have used :

relativeLayout.setBackgroundColor(Color.GRAY);

but I want my color be a little transparent. because I want to user can see below of the my fragment

this is my fragment layout:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    relativeLayout = new RelativeLayout(getActivity());
     rlp = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    relativeLayout.setLayoutParams(rlp);

    return relativeLayout;

}
Answers:

Instead of standard colors from the Color object, you can use a custom HEX color like this:

Color.parseColor("#FFFF00")

Let’s say we want it to have an transparency channel, we can do this:

Color.parseColor("#00ff0000");

The first two digits specify your amount of solid color in the transparency channel, so setting this to zero will make your color fully transparent. You can change them to your needs.

Questions:
Answers:

Use the below code for black:

<color name="black">#000000</color>

Now if I want to use opacity then you can use the below code:

<color name="black">#99000000</color>

And below for opacity code:

Hex Opacity Values

    100% — FF
    95% — F2
    90% — E6
    85% — D9
    80% — CC
    75% — BF
    70% — B3
    65% — A6
    60% — 99
    55% — 8C
    50% — 80
    45% — 73
    40% — 66
    35% — 59
    30% — 4D
    25% — 40
    20% — 33
    15% — 26
    10% — 1A
    5% — 0D
    0% — 00