search
HomeBackend DevelopmentXML/RSS TutorialDetailed explanation of the sample code used in Android XML files

Detailed explanation of the sample code used in Android XML files

1. Layout file: In the layout directory, it is widely used;

We can define two sets for the application Or multiple sets of layouts, for example: you can create new directories layout_land (representing the horizontal screen layout of mobile phones), layout_port (representing the vertical screen layout of mobile phones). The system will automatically find the most appropriate layout file according to different situations, but two different sets of layouts on the same interface The filenames of the files should be the same, just placed in two different directories.

2. Picture files: In the drawable directory, it is divided into three directories from version 2.1 onwards.

drawable-hdpi stores high-resolution pictures, such as WVGA (480×800) ,FWVGA (480×854)

drawable-mdpi stores medium-resolution pictures, such as HVGA (320×480)

drawable-ldpi stores low-resolution pictures, such as QVGA (240×320)

The system will go to these folders to find the corresponding pictures according to the resolution of the machine.​

When developing a program, in order to be compatible with different platforms and different screens, it is recommended that different versions of images be stored in each folder according to needs.

We can put the prepared pictures in this directory, or realize the desired pictures through custom XML files. For example, we can define shape_1.xml and put it in the drawable directory, the content is as follows:

<shape xmlns:android="http://schemas.android.com/apk/res/android"   android:shape="oval"> 
<!--android:shape="oval"表示所要绘制的图形是一个椭圆,默认是rectangle,长方形-->
<gradient 
    android:startColor="#0055ff88" 
    android:centerColor="#0055ff00" 
    android:centerY="0.75" 
    android:endColor="#00320077" 
    android:angle="270" 
/> 
<!--gradient 产生颜色渐变 android:angle 从哪个角度开始变 只有90的整数倍可以 -->
<solid android:color="#ff4100ff"/> 
<!--solid表示图形是实心的,填充里面,#ff4100ff为填充颜色-->
<stroke 
    android:width="2dp"
    android:color="#ee31ff5e" 
    android:dashWidth="3dp" 
    android:dashGap="2dp" /> 
<!-- 描边 采用那样的方式将外形轮廓线画出来,width表示笔的粗细,dashWidth表示小横线的宽度,dashGap表示小横线之间的距离-->
<padding
    android:left="7dp"
    android:top="7dp"
    android:right="7dp" 
    android:bottom="7dp" /> 
<!--和CSS中的padding应该是一个道理-->
<corners android:radius="6dp" /> 
<!--corners表示是有半径为5像素的圆角-->
</shape>

When we want a control to display different pictures according to different states, we can control it directly in the program, or we can create an XML file in the drawable directory to achieve the same effect. For example: we can create a new file button_back in the drawable directory. .xml

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item  android:state_pressed="false"android:drawable="@drawable/xxx1" />
    <item  android:state_pressed="true"  android:drawable="@drawable/xxx2" />
    <item  android:state_focused="true"  android:drawable="@drawable/xxx3" />
    <-- 这里还可以加N多效果和动作 只要你用的到 -->
    <item  android:drawable="@drawable/xxx4" />
</selector>

The above XML file can implement a control (assumed to be a button), get the focus, press the button, and display the effects of different pictures under normal conditions. You only need to reference the file name when defining the control. , for example:

<Button
     android:id="@+id/Button"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@drawable/button_add_x">
</Button>
<!--android:background="@drawable/button_back"指向button_back.xml文件-->

But what should we do when our condition is not an existing event type in the system, for example, ImageView displays different pictures based on the value of a variable var? You can write the following code in the program

if (条件1)
{ 
image.setBackground(R.id.xxx1); 
}
else if (条件2)
{ 
image.setBackground(R.id.xxx2); 
} ...

Or you can use another simple method to achieve the same function. Create an xml file under res/drawable with the following content

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="9" android:drawable="@drawable/battery_0" />
    <item android:maxLevel="39" android:drawable="@drawable/battery_1" />
    <item android:maxLevel="69" android:drawable="@drawable/battery_2" />
    <item android:maxLevel="89" android:drawable="@drawable/battery_3" />
    <item android:maxLevel="100" android:drawable="@drawable/battery_4" />
</level-list>

and then in the layout Set the src of imageview to the created xml file. When changing the image in the program, you only need to use imageview.getDrawable().setLevel(50);
Android will automatically select the corresponding image according to the value of level. The mobile phone uses this method to display different pictures when displaying the remaining battery power.

3. Menu file: In the menu directory, when writing code, you only need to load it with MenuInflater in the onCreateOptionsMenu method. The format is as follows,

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/enabled_item"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_2"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_2"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />
</menu>

4. The resource file is in the values ​​directory. It is called a resource file because the xml files in the values ​​directory all have resource as the root node.

 1 .strings.xml The file that defines strings, the format is as follows:

<resources>
    <string name="hello">Hello World!</string>
    <string name="app_name">我的应用程序</string>
</resources>

2.colors.xml The file that defines colors, the format is as follows:

<resources>
    <!--定义图片颜色-->
    <drawable name="screen_background_black">#ff000000</drawable>
    <drawable name="translucent_background">#e0000000</drawable>
    <drawable name="transparent_background">#00000000</drawable>
    <!--定义文字颜色-->
    <color name="solid_red">#f00</color>
    <color name="solid_blue">#0000ff</color>
    <color name="solid_green">#f0f0</color>
    <color name="solid_yellow">#ffffff00</color>
</resources>

3.arrays.xml The file that defines arrays, The format is as follows:

<resources>
    <string-array name="planets">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
        <item>Pluto</item>
    </string-array>

    <integer-array name="numbers">
        <item>100</item>
        <item>500</item>
        <item>800</item> 
    </integer-array>
</resources>

4.styles.xml The file that defines the style is divided into two purposes:

Style: used in the layout of a single XML element (control) in a unit manner. For example: we can define a style for TextView, including the font size and color of the text, and then use it on a specific instance of TextView.
Theme: used as a unit in all activities in the application or in a certain activity in the application. For example, we can define a Theme, which defines a set of colors for the foreground and background of the window frame and panel, and defines the textable size and color attributes for the menu. This Theme can be applied to all activities in your program.

<resources>
   <!--Theme,可以用来定义activity的主题-->
   <style name="Theme.Transparent">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>
        <item name="android:windowBackground">@drawable/transparent_background</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:colorForeground">#fff</item>
    </style>
    <!--Style,可以用来定义某个View元素,这里是ImageView的样式-->
    <style name="ImageView120dpi">
        <item name="android:src">@drawable/stylogo120dpi</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>
</resources>

Personally, I think that whether it is Theme or Style, it is just the scope of application that is different. The distinction should be based on the xxxx of android:name="xxxx". It is obviously different.

5.dimen.xml File that defines units. There are the following measurement units in Android:

px (pixel): the actual pixels of the screen, the commonly used resolution is 1024* 768pixels means 1024px horizontally and 768px vertically. The display effect is the same on different devices.

in (inch): The physical size of the screen, each inch is equal to 2.54 centimeters.

  mm(millimeters): The physical size of the screen.

  pt (point): The physical size of the screen. 1/72 inch.

  dp/dip: Density-independent pixel, an abstract unit based on screen density. On a 160 dots per inch monitor, 1dp = 1px. However, the ratio of dp to px will change with the change of screen density, and different devices have different display effects.

sp: pixels that have nothing to do with scale, mainly used for font display best for textsize, as a size unit related to text.

<resources> 
    <dimen name="one_pixel">1px</dimen> 
    <dimen name="double_density">2dp</dimen> 
    <dimen name="sixteen_sp">16sp</dimen> 
</resources>

6.attrs.xml The file that defines attributes is mainly used in custom components. The specific usage will be introduced in detail in the subsequent How to use custom components. Its format is as follows:

<resources>     
    <declare-styleable name="MyView">     
        <attr name="textColor" format="color" />     
        <attr name="textSize" format="dimension" />     
    </declare-styleable>     
</resources>

五、动画文件  在anim目录下,动画资源分为两种,

 

1.实现图片的translate、scale、rotate、alpha四种变化,还可以设置动画的播放特性,称为Tween动画。

<set xmlns:android="http://schemas.android.com/apk/res/android">               
    <translate android:interpolator="@android:anim/accelerate_interpolator"
         android:fromXDelta="0" android:toXDelta="200" android:fromYDelta="0"
         android:toYDelta="180" android:duration="2000" />
    <scale android:interpolator="@android:anim/accelerate_interpolator"
         android:fromXScale="1.0" android:toXScale="2.0" android:fromYScale="1.0"
         android:toYScale="2.0" android:pivotX="150%" android:pivotY="150%"
         android:duration="2000" />
    <alpha android:fromAlpha="1.0" android:toAlpha="1.0"
         android:duration="@android:integer/config_mediumAnimTime" />
    <rotate ....各个属性></rotate>
    <Interpolator >可以使用其子类和属性定义动画的运行方式,先快后慢,先慢后快等</Interpolator>
</set>

 

2.帧动画,逐帧播放设置的资源,称为Frame动画。

<animation-list xmlns:android=”http://schemas.android.com/apk/res/android” 
android:oneshot=”true”> 
    <item android:drawable=”@drawable/rocket_thrust1″ android:duration=”200″ /> 
    <item android:drawable=”@drawable/rocket_thrust2″ android:duration=”200″ /> 
    <item android:drawable=”@drawable/rocket_thrust3″ android:duration=”200″ /> 
</animation-list>

六、raw目录下的文件,是直接复制到设备中的任意文件。它们无需编译,添加到你的应用程序编译产生的压缩文件中。一般为应用要用到的音频或视频文件等等

 

   要使用这些资源,可以调用Resources.openRawResource(),参数是资源的ID,即R.raw.somefilename。

七、xml目录下的文件,是程序中需要使用的普通xml文件。在运行时可以通过调用Resources.getXML()读取。

八、assets目录下的文件都是保持原始的文件格式,需要用AssetManager以字节流的形式读取文件。

  1. 先在Activity里面调用getAssets()来获取AssetManager引用。

  2. 再用AssetManager的open(String fileName, int accessMode)方法则指定读取的文件以及访问模式就能得到输入流InputStream。

  3. 然后就是用已经open file 的inputStream读取文件,读取完成后记得inputStream.close()。

  4.调用AssetManager.close()关闭AssetManager。        


总结:其实android中定义如此多的XML配置文件,在我看来就是为了达到显示层和数据层的分离,提高了可维护性,也是我们的程序代码变得简洁。


The above is the detailed content of Detailed explanation of the sample code used in Android XML files. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

From XML to Readable Content: Demystifying RSS FeedsFrom XML to Readable Content: Demystifying RSS FeedsApr 11, 2025 am 12:03 AM

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

Is There an RSS Alternative Based on JSON?Is There an RSS Alternative Based on JSON?Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

RSS Document Tools: Building, Validating, and Publishing FeedsRSS Document Tools: Building, Validating, and Publishing FeedsApr 09, 2025 am 12:10 AM

How to build, validate and publish RSSfeeds? 1. Build: Use Python scripts to generate RSSfeed, including title, link, description and release date. 2. Verification: Use FeedValidator.org or Python script to check whether RSSfeed complies with RSS2.0 standards. 3. Publish: Upload RSS files to the server, or use Flask to generate and publish RSSfeed dynamically. Through these steps, you can effectively manage and share content.

Securing Your XML/RSS Feeds: A Comprehensive Security ChecklistSecuring Your XML/RSS Feeds: A Comprehensive Security ChecklistApr 08, 2025 am 12:06 AM

Methods to ensure the security of XML/RSSfeeds include: 1. Data verification, 2. Encrypted transmission, 3. Access control, 4. Logs and monitoring. These measures protect the integrity and confidentiality of data through network security protocols, data encryption algorithms and access control mechanisms.

XML/RSS Interview Questions & Answers: Level Up Your ExpertiseXML/RSS Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:19 AM

XML is a markup language used to store and transfer data, and RSS is an XML-based format used to publish frequently updated content. 1) XML describes data structures through tags and attributes, 2) RSS defines specific tag publishing and subscribed content, 3) XML can be created and parsed using Python's xml.etree.ElementTree module, 4) XML nodes can be queried for XPath expressions, 5) Feedparser library can parse RSSfeed, 6) Common errors include tag mismatch and encoding issues, which can be validated by XMLlint, 7) Processing large XML files with SAX parser can optimize performance.

Advanced XML/RSS Tutorial: Ace Your Next Technical InterviewAdvanced XML/RSS Tutorial: Ace Your Next Technical InterviewApr 06, 2025 am 12:12 AM

XML is a markup language for data storage and exchange, and RSS is an XML-based format for publishing updated content. 1. XML defines data structures, suitable for data exchange and storage. 2.RSS is used for content subscription and uses special libraries when parsing. 3. When parsing XML, you can use DOM or SAX. When generating XML and RSS, elements and attributes must be set correctly.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools