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的外观或者行为。



















  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值