简体   繁体   中英

how to set background color in the xml layout?

I couldn't find information on how to do this anywhere? I want to define a background color in the xml layout of the activity. How do I do this?

Take your outer layout (eg a LinearLayout ) and set its background attribute to a color.

<LinearLayout android:background="@color/mycolor"
              .... />

These colors can be defined in the res/values/colors.xml file (see here how to do this) .

You can also define a color directly at the attribute ( android:background="#ffff0000" ), but that's usually not good. By defining the colors in the XML file you can give it a descriptive name (improves code readability) and you can reuse it somewhere else.


Edit:
Theres an example in the doc I linked, but here is a short example how it looks:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="red">#ffff0000</color>
    <color name="green">#ff00ff00</color>
</resources>

Its basically a resources tag containing multiple color tags. Each color has a name attribute (which you use to reference the color) and an actual color. That is defined between the color tags in hex. See the docs for possible formats. This one is #AARRGGBB , where A=alpha (transparency) , R=red , G=green and B=blue . This example file contains a full red and a full green color. They can be referenced via @color/red and @color/green .

there is one thing need to mention is that the "android:background="#ffffffff"" setting does not work if this sentence is applied to an include directive.

for example,

<include
    android:id="@+id/fragment_printer_detail_property_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="@dimen/printer_detail_group_vertical_margin"
    android:layout_marginLeft="@dimen/printer_detail_group_horizontal_margin"
    android:layout_marginRight="@dimen/printer_detail_group_horizontal_margin"
    android:layout_marginTop="@dimen/printer_detail_group_vertical_margin"
    layout="@layout/module_printer_detail_property"
    android:background="@color/module_printer_detail_group_background_color" />

the "android:background" should be set in the layout file of module_printer_detail_property.

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