1. 程式人生 > >Android 中各種資原始檔的使用

Android 中各種資原始檔的使用

1、string檔案的使用:         在使用xml中的資源之前,需要在XML檔案中定義:         如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<string name="app_name">CameraDemo1</string>
<string name="people_name">Vincent</string>
<string name="address">Earth</string>
</resources>
已定義的資源可以在其他的xml檔案或者java檔案中使用。
java:
public String getStringResource(){
String s = null;
s = getResources().getString(R.string.people_name);
return s;
}
xml:
<Button
android:text="@string/address"
android:id="@+id/address"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height=
"0dp"
/>
2、array檔案的使用: 在使用xml中的資源之前,需要在XML檔案中定義:        如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="country">
<item>China</item>
<item>Russia</item>
<item>Japan</item>
<item>TailLand</item>
<item>iraq</item>
</string-array>
<integer-array name="number">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</integer-array>
</resources>
java:
public int[] getIntResource(){
Resources rs = getResources();
int[] ints = rs.getIntArray(R.array.number);
if (ints != null){
return ints;
}else{
return new int[]{0};
}
}
public String[] getStringArrayResource(){
Resources rs = getResources();
String[] strings = rs.getStringArray(R.array.country);
if (strings != null){
return strings;
}else{
return new String[]{""};
}
}
xml:在資原始檔中直接引用資源陣列的控制元件,本人很少接觸,只瞭解pinner可以直接使用資源陣列。
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/country">
</Spinner>

3 attr檔案的使用在使用xml中的資源之前,需要在XML檔案中定義:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="size" format="dimension"></attr>
<attr name="color" format="color"></attr>
<attr name="width" format="integer"></attr>
<attr name="picture_resource" format="reference|integer"></attr>
<attr name="view_name" format="string|reference"></attr>
</declare-styleable>
</resources>
需要在xml和java檔案中同時使用檔案引用:一般這種方式的自定義控制元件屬性只能通過使用view的構造方法來獲取view的各個屬性值。程式碼:
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CustomView);
String name = a.getString(R.styleable.CustomView_view_name);
int color = a.getColor(R.styleable.CustomView_color,1234);
a.recycle();
}
xml:
<com.example.zhuyuqiang.camerademo1.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
Mycustom:color="12345"
Mycustom:picture_resource="mipmap/ic_launcher"/>
其實所謂的自定義屬性就是講在xml中所使用的資料出入至View的構造方法中,在構造方法中對自定義的屬性進行解析,獲取裡面的資料,然後根據獲取的資料來影響View的外觀或者行為。