Android使用XML相關技巧解析

來源:互聯網
上載者:User

大家可能還記得,我們在上一篇文章中向大家詳細介紹了Android ListView的相關應用,它主要就是針對於可視化編程。在這裡我們會通過Android使用XML來為大家詳細介紹另一種可視化編程方法。

就如跨平台UI介面庫一樣,Android也是使用XML檔案來存貯界元素持布局,現在流行的一些介面組件都是採用Android使用XML的方式。

在Android中,res/layout資來源目錄下,會有一個或多個.xml檔案,這就是一個介面的布局檔案。我們開啟一個來看看。我開啟當前工程目錄下的res/layout/main.xml檔案。

 
  1. < ?xml version="1.0" encoding="utf-8"?> 
  2. < LinearLayout xmlns:android=
    "http://schemas.android.com/apk/res/android" 
  3. android:orientation="vertical" 
  4. android:layout_width="fill_parent" 
  5. android:layout_height="fill_parent" 
  6. < TextView   
  7. android:layout_width="fill_parent"   
  8. android:layout_height="wrap_content"   
  9. android:text="@string/hello" 
  10. android:id="@+id/mainview" 
  11. /> 
  12. < /LinearLayout> 

這個檔案很簡單的布局是指用了一個LinearLayout來布局,裡面只有一個TextView介面元素,也就是一個View.當Activity載入View時,就可以在onCreate中直接載入。this.setContentView(R.layout.main);其中R.layout.main就是一個素引值,是由android開發環境編譯產生的,是映射到res/layout/main.xml的。

所以setContentView(R.layout.main);等價於,按裝main.xml的布局來配置一個layout.然後載入,與如下代碼效果一致

 
  1. LinearLayout layout = new LinearLayout(this);  
  2. TextView tv = new TextView(this);  
  3. tv.setText(R.string.hello);  
  4. layout.addView(tv);  
  5. this.setContentView(layout); 

其中R.string.hello也是一個資源地圖的ID,是指載入res/values/string.xml中的hello對應的值。

Android使用XML的相關方法就為大家介紹到這裡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.