利用dimens.xml來達到資源的重用

標題是我自己理解的。大意是:有時候我們爲了維護一個工程,或者想定義一個button樣式,或textView樣式,這些樣式中包含着文字的大小,背景圖片,前置圖片等一些資源。而且這個button或textView會在很多地方要用到它,原本我們可以將它的文字大小,圖片樣式等寫在XML中或者代碼中。但這樣的維護性太差了;一旦要修改的時候,需要挨個文件找,挨個修改。現在我們利用dimens來維護時,只需要修改對應的dimens裏定義的值。所有引用它的地方都會自動的修改這樣,我們就達到了維護的目的;

我們可以將要定義的屬性寫在dimens.xml中,以達到資源重複利用;

步驟如下:

1.在values文件夾下建立名爲dimens.xml的文件,如下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.      
  4.     <string name="test_dimen">文本區域</string>  
  5.     <string name="test_dimen1">按鈕</string>    
  6.     <dimen name="text_width">150px</dimen>  
  7.     <dimen name="text_height">100px</dimen>  
  8.     <dimen name="btn_width">30mm</dimen>  
  9.     <dimen name="btn_height">10mm</dimen>  
  10.     <color name="red_bg">#f00</color>  
  11. </resources>   

2.在layout文件夾下建立名爲test_dimens.xml的文件,如下:
[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.      
  7.     <TextView  
  8.         android:text="@string/test_dimen"  
  9.         android:id="@+id/myDimenTextView01"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:width="@dimen/text_width"  
  13.         android:height="@dimen/text_height"  
  14.         android:background="@color/red_bg"  
  15.          
  16.     />  
  17.     <Button   
  18.      android:text="@string/test_dimen1"   
  19.      android:id="@+id/Button01"  
  20.      android:layout_width="wrap_content"  
  21.      android:layout_height="wrap_content"  
  22.      />  
  23. </LinearLayout>   

3.建立類: 

[java] view plaincopy
  1. package com.dim;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.widget.Button;  
  6. import android.content.res.*;  
  7. import com.dim.R;  
  8.   
  9. public class DimensionActivity extends Activity {  
  10.     /** Called when the activity is first created. */  
  11. private Button btn;  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         //設置當前Activity的佈局  
  16.          
  17.         setContentView(R.layout.test_dimens);  
  18.         //獲取Button實例  
  19.         btn=(Button)findViewById(R.id.Button01);  
  20.          
  21.         Resources r=getResources();  
  22.        
  23.         float btn_h =r.getDimension(R.dimen.btn_height);  
  24.         float btn_w =r.getDimension(R.dimen.btn_width);  
  25.          
  26.         btn.setHeight((int)btn_h);  
  27.          
  28.         btn.setWidth((int)btn_w);  
  29.          
  30.         //setContentView(R.layout.main);  
  31.     }  
  32. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章