標籤:android
Android的基本UI介面一般都是在xml檔案中定義好,然後通過activity的setContentView來顯示在介面上,這是Android UI的最簡單的構建方式。其實,為了實現更加複雜和更加靈活的UI介面,往往需要動態產生UI介面,甚至根據使用者的點擊或者配置,動態地改變UI,本文即介紹該技巧。對事件和進程的可能安卓裝置實現觸摸事件的監聽,跨進程
假設Android工程的一個xml檔案名稱為activity_main.xml,定義如下:
| 12345678910111213141516171819 |
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/DynamicText" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> |
在 MainActivity 中,希望顯示這個簡單的介面有三種方式(注:下面的代碼均在 MainActivity 的 onCreate() 函數中實現 )。
(1) 第一種方式,直接通過傳統的 setContentView(R.layout.*) 來載入,即:
| 1234567 |
setContentView(R.layout.activity_main); TextViewtext =(TextView)this.findViewById(R.id.DynamicText); text.setText("Hello World"); |
(2) 第二種方式,通過 LayoutInflater 來間接載入,即:
| 12345678910111213 |
LayoutInflatermInflater =LayoutInflater.from(this); ViewcontentView =mInflater.inflate(R.layout.activity_main,null); TextViewtext =(TextView)contentView.findViewById(R.id.DynamicText); text.setText("Hello World"); setContentView(contentView); |
註:
LayoutInflater 相當於一個“布局載入器”,有三種方式可以從系統中擷取到該布局載入器對象,如:
方法一: LayoutInflater.from(this);
方法二: (LayoutInflater)this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
方法三: this.getLayoutInflater();
通過該對象的 inflate方法,可以將指定的xml檔案載入轉換為View類對象,該xml檔案中的控制項的對象,都可以通過該View對象的findViewById方法擷取。
(3)第三種方式,純粹地手工建立 UI 介面
xml 檔案中的任何標籤,都是有相應的類來定義的,因此,我們完全可以不使用xml 檔案,純粹地動態建立所需的UI介面,樣本如下:
| 1234567891011121314151617 |
LinearLayoutlayout =new LinearLayout(this); TextViewtext =new TextView(this); text.setText("Hello World"); text.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); layout.addView(text); setContentView(layout); |
Android動態UI建立的技巧就說到這兒了,在本樣本中,為了方便理解,都是採用的最簡單的例子,因此可能看不出動態建立UI的優點和用途,但是不要緊,先掌握基本技巧,後面的文章中,會慢慢將這些技術應用起來,到時侯就能理解其真正的應用情境了。