随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
Android的资源布局类型表:
下面通过一个实例演示数组资源的使用,将数组资源的内容显示在界面上:
Activity:
package com.lovo.activity;
import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class TestArrayActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testarray);
// 得到TextView实例
TextView tx = (TextView) findViewById(R.id.tx);
// 得到字符串数组
String[] strAry = getResources().getStringArray(R.array.str_ary);
String str = "";
// 得到整型数组
int[] intAry = getResources().getIntArray(R.array.int_ary);
// 得到普通数组
TypedArray dateAry = getResources().obtainTypedArray(R.array.date);
for (int i = 0; i < intAry.length; i++) {
Log.i("intAry:", intAry[i] + "");// 打印到LogCat
str += intAry[i] + " ";
}
str += "\n";
for (int i = 0; i < strAry.length; i++) {
Log.i("strAry:", strAry[i]);
str += strAry[i] + " ";
}
str += "\n";
for (int i = 0; i < dateAry.length(); i++) {
Log.i("dateAry:", dateAry.getString(i));
str += dateAry.getString(i) + " ";
}
// 将数组中的元素设置到TextView中显示出来
tx.setText(str);
}
}
布局XML,testarray.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tx"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
数组XML:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="str_ary">
<item>张三</item>
<item>李四</item>
<item>王五</item>
</string-array>
<integer-array name="int_ary">
<item>1</item>
<item>2</item>
<item>3</item>
</integer-array>
<array name="date">
<item>昨天</item>
<item>今天</item>
<item>明天</item>
</array>
</resources>