Pro Android Learning Note (iii): Learn about Android resources (top)

Source: Internet
Author: User
Tags getcolor xml reader

In Android development, resources include files or values that are bundled with the application and do not have to be written to die in the source code, so we can change or replace them without recompiling the app.

Understanding Resource Composition

Refer to Reading Android learning notes (38): Resource resource (top), XML parsing (xmlpullparser), Android learning Note (39): Resource resource (bottom).

Strings Resources . Located under Res/values, you can have one or more XML files. One of the most common is Strings.xml, for the demo of this kind of small example, for convenience often all put in the strings.xml, but the actual development, should be reasonable organization. The following things are examples of XML files:

<?xml version="1.0" encoding="Utf-8"?>
<resources>
<string name="app_name">pro android</string>
<string name="action_settings">Settings</string>
<string name="resource_test">understanding resources</string>
</resources>

Be aware that for standard XML files, there is xmlns to indicate the schema, which can be omitted here. If you want to add it, you can: <resources xmlns="http://schemas.android.com/apk/res/android" > . Each definition of a string, in the R.java file will automatically generate an ID, which can be mapped by ID, such as r.string.app_name, id thing int, but Android or converted to the corresponding string as needed.

Public final class R {
... ...
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int resource_test=0x7f050002;
}
... ...
}

Layout Resources . Res/layout The key view, each activity or screen is individually XML to describe. The code is mapped with Setcontentview (R.LAYOUT.XXXX). The view in the layout XML file is mapped with r.id.xxxx and can be Findviewbyid to get the object of the specific view.

Resource Reference Syntax resource reference syntax . The syntax used to assign the ID of a resource in an Android XML file is called the resource reference syntax, specifically @[package:] Type/name, such as android:id= "@+id/t1". "+" means that if the ID of T1 is not defined as a resource, go to define a unique ID number for it. In fact, we can pre-define the ID and use it later, in the following way, as defined in the XML file under Res/values. Once defined, we will find the definition of the R.ID.T2 in the R.java file, so we will use android:id= "@id/t2".

<resources>
<item type= "id" name= "t2"/>
</resources>

The type here is the namespace of the resource class that corresponds to the R.java, for example r.string is string. It can also be Drawable,id,layout,string,attr,plurals,string-array (R.array in R.java). Name here refers to the name of the resource and also to the ID name in R.java. If you do not have a package, use local resources, and R.java in the app. Andriod also provides some components, such as a ListView, using <listview android:id="@android: Id/list".../> this uses Android. R.java file, in real time, we can use the other package name, with the package under the R.java file to explain.

compiled and non-compiled resources . Resource source Two types of files: XML and raw files, corresponding can also be divided into compiled into binary format, and non-compiled direct copy. For a generic resource XML file, the XML node needs to be translated into the ID, so it needs to be compiled as binary. Where res/xml can be placed in any XML format files, as custom, can be r.xml.<file_name> to point to the resource, and the Android provided by the XML reader to parse, such as Xmlpullpaser.

Files that are not compiled as binary are located in Res/raw, and as with all resources under res/, r.raw.<file_name> can be used to obtain the resource. Read is the API that needs to use stream-based, as follows. Audio and video files belong to this kind of raw file, of course, if we need, you can also put an XML file in the Res/raw directory, as raw files to use.

BufferedReader reader=new BufferedReader (New InputStreamReader (Getresources (). Openrawresource (R.raw.w_city_ Code));

Major Key resources

String Arrays. Located in Res/values/*.xml, in the following format:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
<string-array name= "Rt_test_array" >
<item>one</item>
<item>two</item>
<item>three</item>
</string-array>
</resources>

The ID is automatically generated in R.java and can be invoked with r.array.xxxx

Public final class R {
public static final class array {
public static final int rt_test_array=0x7f050000;
}
... ...
}

In the program you can call the following

Gets the activity's resource object through Getresources (), obtaining String-array resources from the object
String strs[] = getresources (). Getstringarray (R.array.rt_test_array);
for (String s:strs) {
......
}

plural plurals. This does not make any sense to Chinese, but in English, there are there is one egg. And there are 5 eggs. The difference. There is a need for a differentiated approach to information representation, and plurals is dealing with it.

There are 6 valid selections in quantity, but if the locale is en, the actual effect is "one" and "other", the rest is set, and the experiment is not effective. The same is true for other language settings, except for Czech, for 2-4, which corresponds to few.

Resources res = getresources (); Get Resource Object
Res.getquantitystring (), the first parameter is the ID of the plurals, the second parameter is 0, corresponding to the selection of quantity, because only 1 and others are valid, the corresponding other, so S1 is there is%d eggs.
String s1= res.getquantitystring (r.plurals.rt_test_plurals, 0);
The second parameter is 0, corresponds to other, and the third parameter is 2, which is the there is 0 eggs based on the format of%d.
S1= res.getquantitystring (R.plurals.rt_test_plurals, 0,2);
The second parameter is 1, which corresponds to one, which is the there is 1 egg.
S1= res.getquantitystring (r.plurals.rt_test_plurals, 1);
The second parameter is 1, corresponding to one, because format does not need to be filled in, for there is 1 egg.
S1= res.getquantitystring (R.plurals.rt_test_plurals, N.);
The second parameter is 2, corresponding to other, because format has input, there is 6 eggs.
S1= res.getquantitystring (R.plurals.rt_test_plurals, 2,6);

Wei: After experimentation, it is possible to replace%d with%s in XML, but if the number of input is more than 1, such as 2 or more, an error will be made at compile time. Plurals just to deal with the problem of plural in Latin, don't make it too complicated. For the above example, the second and third parameters should match, so that it is easy to read, such as res.getquantitystring (r.plurals.rt_test_plurals,6,6).

let's talk about string. String resources can have input and can be in HTML format. Let's look at the fetch and output of the following string resource.

We use the following code to enter the TextView TV.

Tv.append ( getString(r.string.rt_simple_string)));
Tv.append ("\ n"));
...//display string in TV in turn
Tv.append ( getString(r.string.rt_format_string, "World", "my Friend");
...//display string in TV in turn

Pay special attention to the last two. In a resource with HTML format, if you still use <b></b>, when you get the resource, this part of the information disappears, you need to use &lt; and &gt; to represent the left and right angle brackets. A little bit of trouble. In addition, to make the HTML format valid, you need to tell TextView that this is an HTML format, otherwise it will directly display the <b></b> as a string content. The following test proves again the need to rewrite the angle brackets.

Tv.append ( html.fromhtml(getString (rt_html_string1) + "<br/>"));
Tv.append ( html.fromhtml(getString (rt_html_string2) + "<br/>"));

We can refer to string directly in view, such as andriod:text= "@string/rt_simple_string".

Color. The color resource is also defined below res/values/.

<color name= "Rt_blue" > #0000f0 </color>

The code is called as follows. Working with our definitions, we can also use some of the predefined colors of Android, specifically reference http://developer.android.com/reference/android/R.color.html#background_light.

int color = getresources (). GetColor (r.color.rt_blue);
Tv.settextcolor (color);
Tv.setbackgroundcolor (Getresources (). GetColor (android. R.color.background_dark));

Dimension. Similarly, any XML file under Res/values/can be defined

< dimen  name= "RT_DP"; 5 dp </ dimen ,
where DP is the size unit of Android, the dimension units defined in the Android length unit (DP, SP, PX, in, PT, MM, dip)  ,android have the following:
PX (Pixels, pixels)            : corresponds to the actual pixel point on the screen.  
in (Inches, inches)            : Screen physical length units.  
mm (millimeters, mm): The unit of physical length of the screen.  
Pt (Points, lbs)                : Screen physical length unit, 1/72 inch.  
DP (density-independent pixels)     : Logical unit of length, 1dp=1px=1/160 inch on a dpi screen. As the density changes, the corresponding number of pixels also changes, but there is no direct change in proportion.
dip                                       : Same as DP, more for Google samples.  
Sp (pixels independent of density and font scaling): Similar to DP, but can be scaled based on the user's font size preference.

Get dimension from the resource as follows, you can use dimension in Settextsize (), or set the android:textsize= "@dimen/RT_DP" directly in the XML

float dimen = getresources (). Getdimension (R.DIMEN.RT_DP);

Image Resource . Due to the different size of the phone, the same picture can be made into different sizes, placed in the res/drawable-?dpi, the system will be automatically selected, Ic_launcher icon. We can also not consider the actual size of the phone, using the same icon, can be placed in the res/drawable. Test, in order to be simple, to use the same size. The format of the picture can be *.gif,*.jpg and *.png.

In the experiment we put sample_image.png into drawble. In XML, you can refer to the following

The picture in the first image appears stretched

<button android:id= "@+id/vt_button1"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
android:text= "@string/resource_test"
android:background= "@drawable/sample_image"/>
<imagebutton android:id= "@+id/vt_img_button3"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:contentdescription= "@string/resource_test"
android:src= "@drawable/sample_image"/>

Of course, it can also be called in Java encoding. As follows

drawable d = getresources (). getdrawable (R.drawable.sample_image);
Button.setbackground (d);
Equivalent to the following
Button.setbackgroundresource (R.drawable.ic_launcher);
Most of the view has a setbackground approach.

Wei: In the Android API guides this reads: A bitmap graphic file (<.png,. jpg, or. gif). Creates a bitmapdrawable. But getdrawable () returns the drawble. Also according to API Guides, we can set the bitmap XML, and this output bitmapdrawable, the XML is placed under res/drawable/, as follows

<?xml version= "1.0" encoding= "Utf-8"?>
<bitmap
Xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:src= "@[package:]drawable/drawable_resource"
Android:antialias=["true" | "False"]
Android:dither=["true" | "False"]
Android:filter=["true" | "False"]
android:gravity=["Top" | "Bottom" | "Left" | "Right" | "Center_vertical" |
"Fill_vertical" | "Center_horizontal" | "Fill_horizontal" |
"Center" | "Fill" | "Clip_vertical" | "Clip_horizontal"]
android:tilemode=["Disabled" | "Clamp" | "Repeat" | "Mirror"]/>

color-drawable Resources . Outside of the image, the drawable resource can also be color-drawable, a color box. Define a color box that can be added to any XML file in Res/values:

<resource>
<drawable name= "Red_rectangle" > #f00 </drawable>
<drawable name= "Blue_rectangle" > #0000ff </drawable>
<drawable name= "Green_rectangle" > #00f0f0 </drawable>
</resource>

In the view XML, you can also set the

android:background= "@drawable/red_rectangle"

Or in Java code.

Button B1 = (button) Findviewbyid (R.id.vt_button0);
colordrawable grdrawble = (colordrawable) getresources (). getdrawable (R.drawable.green_rectangle);
B1.setbackground (grdrawble);

The actual effect is as follows

A piece of color is not good, to be complex to set up, you need to separate in an XML file, through shape to describe. The file is placed under the res/drawable/directory. Here's what my_round_red_retangle.xml.

<?xml version= "1.0" encoding= "Utf-8"?>
<shape xmlns:android= "Http://schemas.android.com/apk/res/android" >
<solid android:color= "#f0600000"/> <!--This is the bottom---
<stroke android:width= "3DP" android:color= "#ffff8080"/> <!--This is the border--
<corners android:radius= "13DP"/> <!--setting rounded corners--
<padding android:left= "10DP" android:top= "10DP" android:bottom= "10DP" android:right= "10DP"/>
</shape>

The use of Java code is as follows, you can also use android:background= "@drawable/my_round_red_rectangle". Wei: According to the Android API guide, the type used is spandrawable, if so, error, or use gradientdrawable.

Button B2 = (button) Findviewbyid (R.id.vt_button2);
Gradientdrawable Roundtangle = (gradientdrawable) getresources (). getdrawable (R.drawable.my_round_red_rectangle);
B2.setbackground (Roundtangle);

Give another example

<?xml version= "1.0" encoding= "Utf-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"android:shape= "Rectangle">
<gradient android:startcolor= "#ffff0000"
Android:endcolor= "#80ff00ff"
Android:angle= "/>"
<corners android:radius= "8DP"/>
</shape>

RELATED Links: My Android development related articles

Pro Android Learning Note (iii): Learn about Android resources (top)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.