1 Introduction to Android application resources
Android application mainly consists of two parts: code and resources. Resources mainly refer to things related to UI, such as UI layout, strings and pictures. The separation of code and resources allows the application to organize the UI according to the actual needs at run time. In this way, the application only needs to be compiled once to support different UI layouts. This feature allows applications to adapt to different screen sizes and densities, as well as different countries and languages.
2 classification of Android application resources
Android application resources are mainly divided into two categories: assets and res.
2.1 assets resources
Assets class resources are placed in the assets subdirectory of the project root directory. It stores some original files, which can be organized in any way. These files will eventually be packaged in apk files. If we want to access these files in the program, we need to specify the file name to access them. Assuming that there is a file named filename in the assets directory, you can use the following code to access it:
AssetManager am= getAssets(); InputStream is = assset.open("filename");
2.2 res resources
Res class resources are placed in the res subdirectory of the project root directory. Most of the files saved in it will be compiled and given resource ID. In this way, we can access the resources of res class through ID in the program. Res resources can be further divided into the following 9 sub types according to different purposes, as follows:
@1. Animator is saved in res/animator directory as XML file to describe attribute animation.
Attribute animation realizes the animation effect by changing the attributes of the object. The object movement animation can be realized by constantly modifying the coordinate value of the object, or the gradual change effect of the object can be realized by constantly modifying the Alpha channel value of the object.
@2. The anim resource is saved in the res/anim directory as an XML file to describe the make-up animation.
Patching animation is different from attribute animation. It is obtained by implementing a transformation based on the original shape or position of the object. You can apply a rotation transformation to the object to obtain a rotation animation, or you can implement a scaling transformation to the object to obtain a scaling animation. Mathematically speaking, it is to apply a transformation matrix based on the original shape or position of the object to achieve the animation effect.
Note: during the execution of animation, the attributes of the object remain unchanged. What we see is only a deformed copy of it.
@3. The color resource is saved in the res/color directory as an XML file, which is used to describe the color state selector of the object. We can define a selector to specify that an object displays different colors in different states. The status of objects can be divided into pressed, focused, selected, checkable, checked, enabled and window_ 7 kinds such as focused.
@4 drawable resources are saved in res/drawable directory as XML or Bitmap files to describe drawable objects. For example, we can put some pictures (. PNG,. 9. PNG,. JPG,. GIF) in it as the background of the program interface view.
Note: the Bitmap files saved in this directory may be optimized during packaging. For example, a true color PNG file that does not require more than 256 colors may be converted to a PNG panel with only an 8-bit palette, so that the picture can be compressed losslessly to reduce the memory resources occupied by the picture.
In addition, it may also be an XML file compiled into the following Drawable objects:
- BitmapDrawable object
- NinePatchDrawable object
- StateListDrawable object
- ShapeDrawable object
- Animation object
- Other seed class objects of Drawable
@5 layout resources are saved in res/layout directory as XML files to describe the layout of application interface.
@6 menu resources are saved in res/menu directory as XML files to describe the application menu. For example, Options Menu, Context Menu, and Sub Menu.
@7 raw resources are saved in res/raw directory in any format. Like assets resources, they are packaged in apk files, but they will be given resource ID, so that we can access them through ID in the program. Suppose there is a file named filename in the res/raw directory, and it is given the ID r.raw. During compilation Filename, you can access it using the following code:
Resources res = getResources(); InputStream is = res.openRawResource(R.raw.filename);
@8. Resources such as values are saved in the res/values directory as XML files. Generally speaking, they are divided into six values, which are saved in the following files, as shown below:
- arrays. XML (string array, int array) defines array resources
- colors.xml to define color resources
- dimens.xml definition size resource
- strings.xml (integer,bool) defines string resources
- styles.xml definition style resource
@9. Resources such as XML are saved in the res/xml directory as XML files, which are generally used to describe the configuration information of the application.
3 resource usage (color, string, size, array, resource internationalization, layout, menu, adaptive different screen resources)
3.1 color resources (/ res/values directory)
The format code of color XML file is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> //resources root element <color name="black" >#000000</color> //color child element </resouces>
Color definition format description:
- #RGB: R, G and B refer to the values of red, green and blue primary colors respectively (16 levels of 0-f are supported)
- #ARGB: A refers to transparency, and R, G and B refer to the values of red, green and blue primary colors respectively (16 levels of 0-f are supported)
- #RRGGBB: R, G and B refer to the values of red, green and blue primary colors respectively (256 levels of 0-ff are supported)
- #ARRGGBB: A refers to transparency, and R, G and B refer to the values of red, green and blue primary colors respectively (256 levels of 0-ff are supported)
Reference format:
- In java code: r.color color_ Name (this is an int type data used to represent the address of the resource)
- In XML file: @ color/color_name
Method of obtaining color value
getResources().getColor();//Returns a color value in a similar #0000FF format
3.2 string resources (/ res/values directory)
The XML file format code is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="here" >StringHere</string> </resouces>
Reference format:
- In java code: r.string string_ name
- In XML file: @ string/string_name
How to get a string:
Resources.getString(int); //Returns an object of type String
Note: both setText(int resid) and settext (string_name) methods are allowed in the control
3.3 dimension resources (/ res/values directory)
The XML file code is as follows:
<dimen name="dimen_name">18dp</dimen>
Note: the unit of size value can be PX (pixel) or mm (mm, actual screen size) or dp
Reference format:
- java code: r.dimension dimen_ name
- In XML file: @ dimension / dimension_ name
How to obtain size resources:
Resources.getDimension(R.dimen.dimen_name);//Returns an object of type float
Note: the return value of this method is of float type, and the setWidth() parameter is required to be of int type, so it needs to be cast.
3.4 array resources (/ res/values directory)
3.4.1 array resource base
Create array resources, and create arrays. In the values directory xml file, and then in arrays The < string array > or < integer array > tags are used in xml to define arrays. The xml configuration is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="languages"> <item>cxx</item> <item>java </item> <item>php</item> <item>xml</item> <item>html</item> </string-array> <integer-array name="reminder_methods_values" translatable="false"> <item>1</item> <item>2</item> <item>3</item> </integer-array> </resources>
Where: < array > is an ordinary array, < string array > defines a character array, < integer array > is an integer array.
3.4.2 reference array resources
There are two ways to reference array resources: reference in code and reference in xml file, as follows:
@1 reference in java code
Resources res =getResources(); String[] languages = res.getStringArray(R.array.languages); String[] reminder_methods = res.getIntArray(R.array.reminder_methods_values);
In addition, you can also obtain an ordinary array of TypedArray type through obtainTypedArray(int ResId). This class provides getXXX(int index) method to obtain the array elements at the specified index.
@2 reference in xml (take spinner control as an example here, because the entries attribute of Spinner just needs array resources)
<Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/languages" />
Note: the reference above is @ array.
3.5 resource internationalization (/ RES / drawable zh RCN hdpi Directory & / RES / values - language code - r - country code directory)
@1 string Internationalization: just create a new values folder for the corresponding language under the res folder.
Android internationalization
Use XML resource files to manage all string messages. The naming methods of different values folders are: values - language code - r - country code, such as values zh RCN and values en Rus
Note: when creating a new Android project, a default locale folder values will be automatically created in the res directory. When a resource is not found in the corresponding resource set of the locale, the resource under values will be used. If a locale is not defined in the project, the resources under values will also be used, which is to use XML files for resource configuration.
@2 picture internationalization
Create a new drawable zh folder under res to store pictures in Chinese environment, and then create drawable en as pictures in English environment. The picture name is interpreted as follows:
When creating a new Android project, three default locale folders will be automatically created in the res Directory: drawable hdpi | drawable LDPI | drawable MDPI, which are used to store high, medium and low resolution pictures respectively. The Android system will automatically load pictures from different corresponding folders according to the resolution of the mobile phone. Similarly, they can also be internationalized. The naming rule is: drawable language code r country code resolution, such as drawable zh RCN hdpi or drawable en Rus MDPI. The usage is as follows:
- Use the expression @ drawable/icon where the image needs to be used in the XML file
- Used in Code: r.drawable icon. The Android environment itself will find the corresponding image according to the index
3.6 layout resources (/ res/layout directory)
Layout resources are generally defined in Android projects:
- In the XML file, you can access it through the following syntax format: @ layout / < file_ name>
- In Java code, access it according to the following syntax format: r.layout< file_ name>
3.7 menu layout resources (/ res/menu directory)
menu resources are generally defined in Android projects:
- In the XML file, you can access it through the following syntax format: @ menu / < file_ name>
- In Java code, access it according to the following syntax format: r.menu< file_ name>
3.8 adaptive different screen resources
Features of Android Applications: the screen size and resolution are very different, but the application should work normally on all devices. In order to adapt to the resources of different screens, the simplest way is to provide corresponding layout files and Drawable resources for different screen sizes and screen resolutions.
Generally speaking, screen resources need to consider the following three aspects:
- Screen size: small, normal, large, XLarge
- Screen resolution: LDPI (low resolution), MDPI (medium resolution), hdpi (high resolution), xhdpi (ultra high resolution)
- Screen orientation: it is divided into land (horizontal screen) and port (vertical screen). It is necessary to establish layout port and layout land directories under res directory, and place vertical screen and horizontal screen layout files respectively to adapt to the automatic switching of horizontal screen and vertical screen.
The automatic selection of layout resource and Drawable resource directory is described as follows:
- Android divides the drawable directory into four by default (drawable xhdpi | drawable hdpi | drawable - MDPI | drawable LDPI), which mainly select different drawable resource files according to different resolutions.
- The layout file layout directory (layout small | layout normal | layout large | layout XLarge) mainly selects different layout files according to different resolutions.
3.9 special instructions on resource reference
In fact, Android system makes no distinction between all xml resource files. It thinks that the value resource type lies not in the file, but in the tag name. For example, the tag name of string array determines that it is an array resource. Understand the principle, but in the end, it is recommended to put these resources in the corresponding position, which is also an unwritten rule of Android.
4. Use Drawable resources (/ res/drawable)
Drawable resources are usually saved in the / res/drawable directory. In fact, they may be saved in the / res/drawable LDPI, / res/drawable MDPI, / res/drawable hdpi directories.
4.1 picture resources
@1 image resources are generally defined in Android projects
- In the XML file, you can access it through the following syntax format: @ drawable / < file_ name>
- In Java code, access it according to the following syntax format: r.drawable< file_ name>
@2 in the program, in order to obtain the actual Drawable object, Resources provides the Drawable getDrawable(int ResId) method
Note: Android requires that the file name of the image resource must comply with the identifier naming rules of Java, otherwise the SDK cannot generate the resource index in the R class for the image
4.2 statelistdrawable resources
4.2.1 StateListDrawable Foundation
A StateListDrawable is defined in an xml file. According to different states of the object, several different pictures are used to represent the same graph. StateListDrawable is used to organize multiple Drawable objects and will automatically switch with the change of the state of the target component. For example, a button has multiple states, such as getting focus, losing focus, clicking, etc. StateListDrawable can provide different picture backgrounds according to different states.
Note: these status lists are described in the XML file. Under the only < selector > tag, use the < item > tag to represent a graph. Each < item > tag uses various attributes to describe the drawable resources required by the state it represents. When the state changes again, the state list will be traversed from top to bottom, and the first matching will be used (instead of selecting the most suitable matching).
The syntax format is as follows:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize=["true" | "false"] android:dither=["true" | "false"] android:variablePadding=["true" | "false"] > <item android:drawable="@[package:]drawable/drawable_resource" android:state_pressed=["true" | "false"] android:state_focused=["true" | "false"] android:state_hovered=["true" | "false"] android:state_selected=["true" | "false"] android:state_checkable=["true" | "false"] android:state_checked=["true" | "false"] android:state_enabled=["true" | "false"] android:state_activated=["true" | "false"] android:state_window_focused=["true" | "false"] /> </selector>
4.2.2 detailed interpretation of attributes
For the XML attribute in StateListDrawable, see the official document: Detailed interpretation of StateListDrawable XML attribute
4.2.3 application examples
@1 here is an example of Button using selector, as shown below:
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Default background image --> <item android:drawable="@drawable/pic1" /> <!-- Background image without focus --> <item android:state_window_focused="false" android:drawable="@drawable/pic1" /> <!-- Background image when focus is obtained and clicked in non touch mode --> <item android:state_focused="true" android:state_pressed="true" android:drawable= "@drawable/pic2" /> <!-- Background picture when clicking in touch mode --> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pic3" /> <!--Picture background when selected --> <item android:state_selected="true" android:drawable="@drawable/pic4" /> <!--Picture background when getting focus --> <item android:state_focused="true" android:drawable="@drawable/pic5" /> </selector>
@2 this is an example of EditText using selector, as shown below:
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Specifies the color when you get focus --> <item android:state_focused="true" android:color="#f44"/> <!-- Specifies the color when the focus is lost --> <item android:state_focused="false" android:color="#eee"/> </selector>
4.3 Layerdrawable resources
4.3.1 # LayerDrawable Foundation
LayerDrawable is a drawable that manages a group of drawable objects (essentially layer overlay). The drawable resources in LayerDrawable are drawn in the order of the list, and the last drawable in the list is drawn at the top. It can be used for overlay display of layers and redrawing themes and effects with controls such as SeekBar. It contains a group of drawable resources represented by multiple < item > elements, and one < item > element represents a drawable resource.
The syntax format is as follows:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/black_lotus" android:left="20dp" android:top="20dp"> </item> <item android:drawable="@drawable/black_lotus" android:left="40dp" android:top="40dp"> </item> <item android:drawable="@drawable/black_lotus" android:left="60dp" android:top="60dp"> </item> </layer-list>
4.3.2 detailed interpretation of attributes
For the XML attribute in LayerDrawable, see the official document: Detailed interpretation of LayerDrawable XML attribute
Note: by default, all drawable item s will be scaled to the appropriate size to fit the view. Therefore, defining different positions in a layer list may increase the size of the view and be automatically scaled. To avoid being scaled, you can add a < bitmap > element to the < item > node to specify a drawable, and define some gravity attributes that will not be stretched, such as center. Next, define a drawable in the item, and the image will be automatically scaled to fit the size of the view.
<item android:drawable="@drawable/image" />
To avoid scaling, you can specify drawable resources using child elements of < bitmap >
<item><bitmap android:src="@drawable/image" android:gravity="center" /></item>
4.3.3 application examples
@1 this is an example of layer list used by SeekBar, as shown below:
<?xml version="1.0" encoding="UTF-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Define the background of the track --> <item android:id="@android:id/background" android:drawable="@color/black" /> <!-- Defines the appearance of the finished portion of the track--> <item android:id="@android:id/progress" android:drawable="@color/cyan" /> </layer-list>
@2. This is an example of graphic overlay, as shown below:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <bitmap android:src="@drawable/ic_launcher" android:gravity="center" /> </item> <item android:top="25dp" android:left="25dp"> <bitmap android:src="@drawable/ic_launcher" android:gravity="center" /> </item> <item android:top="50dp" android:left="50dp"> <bitmap android:src="@drawable/ic_launcher" android:gravity="center" /> </item> </layer-list>
4.4 shapedrawable resources
4.4.1 shapedrawable Foundation
shapeDrawable is used to define a basic geometric figure (rectangle, circle, line, etc.), which can reduce the workload of art workers and draw a better background picture.
The syntax format is as follows:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape=["rectangle" | "oval" | "line" | "ring"] > <corners android:radius="integer" android:topLeftRadius="integer" android:topRightRadius="integer" android:bottomLeftRadius="integer" android:bottomRightRadius="integer" /> <gradient android:angle="integer" android:centerX="integer" android:centerY="integer" android:centerColor="integer" android:endColor="color" android:gradientRadius="integer" android:startColor="color" android:type=["linear" | "radial" | "sweep"] android:useLevel=["true" | "false"] /> <padding android:left="integer" android:top="integer" android:right="integer" android:bottom="integer" /> <size android:width="integer" android:height="integer" /> <solid android:color="color" /> <stroke android:width="integer" android:color="color" android:dashWidth="integer" android:dashGap="integer" /> </shape>
4.4.2} detailed interpretation of attributes
For XML attributes in ShapeDrawable, see the official document: Detailed interpretation of ShapeDrawable XML attribute
4.4.3 application examples
@1. Use example of line (line)
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line"> <stroke android:width="10dp" android:color="#FF0000FF" android:dashWidth="1dp" android:dashGap="1dp" /> </shape>
@2 example of rectangle (rounded rectangle)
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- Defines the fill gradient color --> <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF" android:angle="45"/> <!-- Set inner fill --> <padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" /> <!-- Set rounded rectangle --> <corners android:radius="8dp" /> <!-- Set border --> <stroke android:width="3dip" android:color="#ff0" /> </shape>
@3. Application examples of oval (ellipse)
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <!-- Defines the fill gradient color --> <gradient android:startColor="#ff0" android:endColor="#00f" android:angle="45" android:type="sweep"/> <!-- Set inner fill --> <padding android:left="7dp" android:top="7dp" android:right="7dp" android:bottom="7dp" /> <!-- Set fillet --> <corners android:radius="8dp" /> </shape>
@4. Application example of ring (ring)
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="ring" android:innerRadius="12dp" android:innerRadiusRatio="1" android:thickness="0dp" android:thicknessRatio="4" android:useLevel="false" > <stroke android:width="1dp" android:color="#ff0000" /> <solid android:color="#ff0000" /> </shape>
4.5 clipdrawable resources
4.5.1 ClipDrawable Foundation
ClipDrawable is used to cut a drawable, which can control the cutting area of the drawable and the alignment relative to the container. The progress bar in android uses a ClipDrawable to achieve the effect. It determines the size of the cutting area according to the attribute value of level.
Note: ClipDrawable controls the image cutting operation according to the size of the level. It is mentioned in the note of the official document that the size of the level ranges from 0 to 10000. When the level is 0, it will not be displayed at all, and when it is 10000, it will be displayed at all. Use the setLevel (int level) method provided by Drawable to set the cutting area.
The syntax format is as follows:
<?xml version="1.0" encoding="utf-8"?> <clip xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/drawable_resource" android:clipOrientation=["horizontal" | "vertical"] android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" | "fill_vertical" | "center_horizontal" | "fill_horizontal" | "center" | "fill" | "clip_vertical" | "clip_horizontal"] />
4.5.2 detailed interpretation of attributes
For the XML attribute in ClipDrawable, see the official document: Detailed interpretation of ClipDrawable XML attribute
4.5.3 application examples
Here, a dynamic instance (code + configuration) is used to realize a special effect {the ClipDrawable object is used to call the setLevel method to control the part of the intercepted picture. Therefore, this example sets a timer to let the program continuously call the setLevel method of ClipDrawable to realize the effect of slowly expanding the picture}
@1 code is as follows:
public class ClipDrawableTest extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main4); ImageView imageView = (ImageView) findViewById(R.id.image); final android.graphics.drawable.ClipDrawable drawable = (android.graphics.drawable.ClipDrawable) imageView.getDrawable(); final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x1233) { drawable.setLevel(drawable.getLevel() + 200); } } }; final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Message msg = new Message(); msg.what = 0x1233; handler.sendMessage(msg); if (drawable.getLevel() >= 10000) { timer.cancel(); } } }, 0, 300); } }
Note: the usage of ClipDrawable is defined to convert the Drawable.
@2 my_clip.xml implementation
The key is that android:sec="@drawable/my_clip" calls this configuration file. The contents of this configuration file are:
<?xml version="1.0" encoding="UTF-8"?> <clip xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/test" android:clipOrientation="horizontal" android:gravity="center"> </clip>
The key here is to control the display effect by alignment and display direction, that is, gravity and clipOrientation.
@3 main. Contents of XML file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/image" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/my_clip" /> </LinearLayout>
This is a clipDrawable configuration file. Call a clip configuration file to show the effect.
5 attribute resources
5.1 XML attribute resource base
It is mainly aimed at the attributes of custom components. The specific format is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="test" format="string" /> <declare-styleable name="MyView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> <attr name="text" format="string" /> </declare-styleable> </resources>
A styleable object is defined here, and each styleable object is a set of attr attributes (Note: the name attribute here does not have to be the same as the user-defined class name, just to distinguish the attributes of the corresponding class).
Definition of attr attribute resource: name defines the specific attribute name, and format represents the attribute value type. There are the following types:
- Reference: refers to the resource ID in the specified Theme. This type indicates that the value you pass can be a reference resource.
- String: if you want to reference resources in a way similar to "@ string/test", you can write it as format="string /reference"
- Color: color
- boolean: boolean value
- Dimension: dimension value
- float: floating point type
- Integer: integer
- fraction: percentage
- flag: bit or operation
- enum: enumeration. If the attribute you provide can only be selected by others and cannot be passed in casually, it can be written like this
<attr name="language"> <enum name="china" value="1"/> <enum name="English" value="2"/> </attr>
Note: this attribute resource file is public, but in order to facilitate management, the attributes in a custom View are generally written into a declare styleable collection. The function of the attribute defined by the attribute resource depends on the code implementation of the custom component
5.2 examples of matching XML attribute resources
Write out the class file of the custom component, and then define the attributes in this class that need external input values as an attribute resource file.
In the project/ Create an attrs XML file (the file name can only be written in this way. It has only one purpose. Others will know that this file is an attribute resource file at a glance). The specific writing method is as follows:
@1 attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="test1" format="string" /> <declare-styleable name="MyView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> <attr name="text" format="string" /> </declare-styleable> </resources>
@2. Reference the attribute defined in attrs file in the user-defined class and set the value for its own attribute. The code implementation is as follows:
public class MyView extends View { private Paint mPaint; private Context mContext; private static String mString; private String test; public MyView(Context context) { super(context); mPaint = new Paint(); } public MyView(Context context,AttributeSet attrs) { super(context,attrs); mPaint = new Paint(); /*Open the resource and get the declare styleable collection*/ TypedArray typeArray = context.obtainStyledAttributes(attrs,R.styleable.MyView); /*Get the corresponding attribute value from the collection. The second parameter is the default value used when the attribute is not configured*/ int textColor = typeArray.getColor(R.styleable.MyView_textColor,0XFFFFFFFF); float textSize = typeArray.getDimension(R.styleable.MyView_textSize, 36); mString = typeArray.getString(R.styleable.MyView_text); /*Set your own class member variables*/ mPaint.setTextSize(textSize); mPaint.setColor(textColor); /*close resource*/ typeArray.recycle(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setStyle(Style.FILL); canvas.drawRect(new Rect(10, 10, 90, 90), mPaint); mPaint.setColor(Color.BLUE); canvas.drawText(mString, 10, 110, mPaint); } }
@3 use custom components and set properties
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:myandroid="http://schemas.android.com/apk/res/com.ags.androidtest" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"/> <cn.com.androidtest.ui.MyView android:layout_width="fill_parent" android:layout_height="wrap_content" myandroid:textColor="#ff0000" myandroid:textSize="20px" myandroid:text="myview"/> </LinearLayout>
be careful:
When using this component in XML, you need to set a namespace for this custom component. The namespace is written as follows:
<XXX xmlns:Space name="http://schemas.android.com/apk/res / package name of custom component "/ >
When writing the package name, under the folder of the package class where your custom View is located, the package name can only be written as the top-level package [com.ags.androidtest], not [com.ags.androidtest.xxx].
6 RAW resources
Files that do not provide special support in android are called original resource files. android raw resources are generally placed in the / res/raw directory and / assets / directory.
6.1 index acquisition of original documents
@1. Files in the assets directory
Assets are managed through assetmanager. Generally, the following methods are used to access assets resources
//Obtain the input stream corresponding to the original resource according to the file name InputStream open(String fileName) //Obtain the AssetFileDescriptor resource description of the original resource pair according to the file name, and the application can obtain the original resource through it AssetFileDescriptor openFd(String fileName)
@2. Files in RES / raw directory
The Android SDK will process the original resources in this directory and generate index entries for the resources in this directory in the R list class
- The xml file can be accessed through the following syntax format: @ [< package_name >:] raw / file_ name
- Access in Java files according to the following syntax: r.raw< file_ name>
6.2 use cases
There are mainly two ways to obtain resources and realize the function of playing sound by using MediaPlayer class. The code is as follows:
public class RawResTest extends AppCompatActivity { MediaPlayer mediaPlayer1 = null; MediaPlayer mediaPlayer2 = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Method 1: create MediaPlayer object 1 directly according to the ID of the sound file. mediaPlayer1 = MediaPlayer.create(this, R.raw.bomb); //Method 2: get the AssetManager of the application AssetManager am = getAssets(); try { //Gets the AssetFileDescriptor corresponding to the specified file. AssetFileDescriptor afd = am.openFd("shot.mp3"); mediaPlayer2 = new MediaPlayer(); //Use MediaPlayer to load the specified sound file. mediaPlayer2.setDataSource(afd.getFileDescriptor()); mediaPlayer2.prepare(); } catch (IOException e) { e.printStackTrace(); } // Get the first button and bind it to an event listener Button playRaw = (Button) findViewById(R.id.playRaw); playRaw.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //Play sound mediaPlayer1.start(); } }); // Get the second button and bind it to an event listener Button playAsset = (Button) findViewById(R.id.playAsset); playAsset.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //Play sound mediaPlayer2.start(); } }); } }
7 style and theme
7.1 style resources
7.1.1 resource introduction
If you often specify roughly similar formats for a certain type of component, specifying these attributes repeatedly for the View component every time will lead to a lot of workload, which is not conducive to the later maintenance of the project. A style is equal to a set of formats. If a certain style is used for a certain text, the format will be applied to the text as a whole; Similar to this, Android style also contains a set of formats when a style is set for a component. All formatting contained in the style will be applied to the component.
A style is a collection of attributes, such as defining the attributes fontColor, fontSize, and layout_width,layout_height, etc. are stored in the XML file as an independent resource file, and the name of the style is set.
Style resource creates a Style XML resource file under res/values /. The style resource file created here is named styles XML, which can be customized by yourself.
7.1.2 style resource syntax rules
styles. The syntax format of XML is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="wrap_content"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> </style> </resources>
Android Style (similar to CSS design idea in the Web) separates design from content, and can be easily inherited and covered.
7.1.3 style inheritance
There are two ways to inherit style:
- Through the parent attribute of style.
- Use naming rules similar to those in CSS.
They are interpreted as follows:
@1. Modify styles through the parent attribute XML is implemented as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="wrap_content"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> </style> <style name="inherit" parent="wrap_content"> <item name="android:textColor">#00FF00</item> </style> </resources>
Add a new style named inherit and inherit the name wrap_content style, that is, inherit has wrap_ Attribute parameters defined in content style. The reference method is: style="@style/inherit".
@2. It is realized by naming rules. The xml configuration code is as follows:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="wrap_content"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> </style> <style name="wrap_content.inherit"> <item name="android:textColor">#00FF00</item> </style> </resources>
By "." No. implements inheritance. Reference method: style="@style/wrap_content.inherit"
7.1.4 use cases of style layout
Examples of using styles in layout files are as follows:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView style="@style/wrap_content" android:textColor="#00FF00" android:text="@string/hello" /> <TextView style="@style/wrap_content" android:text="@string/hello" /> <Button style="@style/wrap_content" android:text="@string/hello" /> </LinearLayout>
Finally, summary: style is the encapsulation of the UI properties of the control, which is convenient for reuse.
7.2 # theme resources
7.2.1 basic concepts
- Difference between theme resource and style: theme cannot be used for a single View component. It works on all activities or specified activities of the whole application.
- Theme format: change the format of window appearance, such as window title, window border, etc.
7.2.2 configuration and use theme
Here, a new theme is added through a case (the theme with border and background is added to all windows) and the theme is defined in the XML file. The configuration is as follows:
<?xml version="1.0" encoding="UTF-8"?> <resources> <style name="AgsTheme"> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowFrame">@drawable/window_border</item> <item name="android:windowBackground">@drawable/star</item> </style> </resources>
@1 at androidmanifest Using themes in XML files
Specify a specific topic in the android:theme attribute of application. The configuration is as follows:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ags.res" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AgsTheme"> <activity android:name=".StyleResTest" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Note: several built-in theme resources are provided in Android. You can query Android R. The style class can see the themes that Android has designed. Themes are the same as styles, and can be customized through integration. The reference template is as follows:
<resources> <style name="AgsTheme" parent="@android:style/Theme.Dialog"> ... </style> </resources>
@2. Use the theme in the code as follows:
public class StyleResTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.CrazyTheme);//be careful: setContentView(R.layout.main); } }