Android資源文件詳解

jopen 10年前發布 | 17K 次閱讀 Android Android開發 移動開發

一、color 顏色資源

res/values/Color.Xml文件

<resources>

<color name=”red_bg”>#f00</color >

</resources >

資源文件引用資源文件,設置lovo字體顏色為紅色

res/layout/color.xml

<TextView

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”lovo”

android:textColor=”@color/red_bg”>

</TextView >

 

Java代碼引用顏色資源:

//引用顏色資源,設置背景色為紅色

 getWindow().setBackGroundDrawableResource(R.color.red_bg)

 

二、字符串 string資源

 

res/values/string.Xml文件

<resources>

<string name=”test1_str”>從代碼中引用</ string>

<string name=”test2_str”>從資源文件中引用</ string>

</resources >

res/layout/string.xml

資源文件中引用字符串

<TextView

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=”@string/test1_str

/>

 

< TextView

Android:id=”@+id/text_view”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:text=””

/>

代碼中設置字符串:

//獲取到文本視圖對象

TextView text=( TextView)findViewById(R.id.text_view);

//從string資源文件中得到字符串

String str = getString(R.string.test2_str);

//把從資源文件中獲取到的字符串顯示在文本視圖上

text.setText(str);

 

三、尺寸 dimen

尺寸單位:px 絕度像素,是多少就顯示多少

           dp和密度無關的像素 在不同的設備上顯示的效果相同

           sp和精度無關的像素 一般作為字體的像素

res/values/dimen.Xml文件

<resources>

< dimen name=”text_width”>100dp</dimen >

< dimen name=”btn_width”>120dp dimen>

</resources >

res/layout/btn_layout.xml

資源文件中引用尺寸

<Button android:width=”@dimen/btn_width”

android:id=”@+id/button”/>

//獲得按鈕對象

Button btn=(Button)findViewById(R.id.button);

//獲得resources實例

Resouces r = getResouces();

//通過getDimension()方法獲得尺寸值

Float btn_w = r.getDimension(R.dimen.button);

//設置按鈕的尺寸

Btn.setWidth((int)btn_w);

 

四、drawables資源

res/layout/pic.Xml文件

<ImageView

android:layout_width=”macth_parent”

android:id=”@+id/pic”

android :background=”@drawable/g”

/>

在代碼中獲得圖片:

//找到ImageView對象

ImageView img = (ImageView)findViewById(R.id.pic);

//得到resources實例

Resouces r = getResouces();

//通過Resouces獲得Drawable對象

Drawable d= r.getDrawable(R.drawable.mt);

//設置ImageView的ImageDrawable屬性顯示圖片

Img.setImageDrawable(d);

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!