Android的基本UI界面一般都是在xml文件里定義好,然后通過activity的setContentView來顯示在界面上。這是Android UI的最簡單的構建方式。事實上,為了實現更加復雜和更加靈活的UI界面。往往須要動態生成UI界面,甚至依據用戶的點擊或者配置,動態地改變UI。本文即介紹該技巧。對事件和進程的可能安卓設備實現觸摸事件的監聽。跨進程
如果Androidproject的一個xml文件名稱為activity_main.xml,定義例如以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<
LinearLayout
xmlns
:
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.*) 來載入,即:
1
2
3
4
5
6
7
|
setContentView
(
R
.
layout
.
activity_main
)
;
TextView
text
=
(
TextView
)
this
.
findViewById
(
R
.
id
.
DynamicText
)
;
text
.
setText
(
"Hello World"
)
;
|
(2) 另外一種方式。通過 LayoutInflater 來間接載入,即:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
LayoutInflater
mInflater
=
LayoutInflater
.
from
(
this
)
;
View
contentView
=
mInflater
.
inflate
(
R
.
layout
.
activity_main
,
null
)
;
TextView
text
=
(
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界面,示比例如以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
LinearLayout
layout
=
new
LinearLayout
(
this
)
;
TextView
text
=
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的長處和用途,可是不要緊,先掌握基本技巧,后面的文章中,會慢慢將這些技術應用起來,到時侯就能理解其真正的應用場景了。