您的位置:首页 > 移动开发 > Android开发

2012-6-13 Android中的资源访问——尺寸资源

2013-01-13 17:36 337 查看
、Android支持的尺寸资源





2、尺寸资源XML文件的定义



3、尺寸资源XML文件的使用

该示例在布局文件中添加一个TextView和一个Button,分别使用尺寸资源来定义它们的宽和高。

1)、在工程的res\values\目录下添加一个dimens.xml尺寸资源文件,并且添加4个尺寸资源(如下面代码所示),可视化的添加方法跟添加字符串类似,不过其Value值要是“数字+单位”(我自己的体会)。当然你也可以直接输代码。

<?xml version="1.0" encoding="utf-8"?>

<resources>

<dimen name="test_width">150px</dimen>

<dimen name="test_height">100px</dimen>

<dimen name="btn_width">30mm</dimen>

<dimen name="btn_height">10mm</dimen>

</resources>

2)、在工程的res\layout\目录下添加一个test_dimens.xml布局资源文件,在布局文件中添加一个TextView和一个Button,TextView的宽高尺寸引用尺寸资源来设置,Button的宽和高在代码中设置:

<TextView

android:text="@string/test_demen"

android:id="@+id/myTextView01"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="@color/blue_text"

android:width="@dimen/test_width"

android:height="@dimen/test_height"

android:background="@color/red_bg"

/>

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/test_demen1" />

3)、Button宽和高设置代码

   Button myButton = (Button)findViewById(R.id.button1);

Resources r = getResources();

float btn_h = r.getDimension(R.dimen.btn_height);

float btn_w = r.getDimension(R.dimen.btn_width);

myButton.setHeight((int)btn_h);

myButton.setWidth((int)btn_w);

总的来说,尺寸资源和字符串资源的使用很相似。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: