歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發技巧:動態創建UI界面

Android開發技巧:動態創建UI界面

日期:2017/3/1 9:54:41   编辑:Linux編程

Android的基本UI界面一般都是在xml文件中定義好,然後通過activity的setContentView來顯示在界面上,這是Android UI的最簡單的構建方式。其實,為了實現更加復雜和更加靈活的UI界面,往往需要動態生成UI界面,甚至根據用戶的點擊或者配置,動態地改變UI,本文即介紹該技巧。

假設Android工程的一個xml文件名為activity_main.xml,定義如下:

<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.*) 來加載,即:

setContentView(R.layout.activity_main);

TextView text = (TextView)this.findViewById(R.id.DynamicText);
text.setText("Hello World");

(2) 第二種方式,通過 LayoutInflater 來間接加載,即:

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界面,示例如下:

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的優點和用途,但是不要緊,先掌握基本技巧,後面的文章中,會慢慢將這些技術應用起來,到時侯就能理解其真正的應用場景了。

Copyright © Linux教程網 All Rights Reserved