編輯:關於 Android 程式設計
有時候我們需要根據不同的需求動態決定 App 頁面的佈局,例如依伺服器回傳的條目數量,來決定頁面上要顯示幾個控件、哪些圖示等。本文就來示範如何用 Java 程式碼完成動態佈局。


先在 XML 裡準備一個空的父容器(這裡用 LinearLayout),後續動態生成的圖片與文字都會加進這個容器裡。
每一個子項目用一個 FrameLayout,裡面放一個 ImageView(圖示)與一個 TextView(文字):

核心思路是:把文字資源定義在 array 檔案裡,讀取出來後依數量計算需要幾列,再用迴圈動態 inflate 子佈局並填進父容器。
/**
* @author gao_chun
*/
public class MainActivity extends Activity implements OnClickListener{
private ViewGroup mMoreLayout; // 父容器(動態生成的資源都加在這裡)
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initUI();
}
private void initUI() {
setContentView(R.layout.activity_main);
// 找到容器(這裡是 LinearLayout,轉型為 ViewGroup 是因為它是所有容器的基類)
mMoreLayout = (ViewGroup) findViewById(R.id.layout_more);
// 文字也是動態生成,用 array 資源定義並取出
final String[] categories = getResources().getStringArray(R.array.categories);
final int size = categories.length;
final int rowCount = size / 3; // 每行三個,計算需要幾列
fillViews(mMoreLayout, categories, 0, rowCount);
}
private void fillViews(ViewGroup layout, String[] categories, int start, int end) {
// 表格第一條橫線
View.inflate(this, R.layout.layout_line_horizonal, layout);
for (int i = start; i < end; i++) {
final int firstIndex = i * 3;
final int secondIndex = i * 3 + 1;
final int thirdIndex = i * 3 + 2;
final String firstCategory = categories[firstIndex];
final String secondCategory = categories[secondIndex];
final String thirdCategory = categories[thirdIndex];
// 依規則命名找到本地圖片資源(分為預設圖與按下圖兩種)
final int firstDrawableNormal = getResources().getIdentifier(String.format("ic_department_%02d_normal", firstIndex + 1), "drawable", getApplicationContext().getPackageName());
final int firstDrawablePressed = getResources().getIdentifier(String.format("ic_department_%02d_pressed", firstIndex + 1), "drawable", getApplicationContext().getPackageName());
// 其餘 second、third 同理,這裡省略
// 把預設圖與按下圖放進 StateListDrawable 快取
final StateListDrawable firstDrawable = new StateListDrawable();
firstDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(firstDrawablePressed));
firstDrawable.addState(new int[]{}, getResources().getDrawable(firstDrawableNormal));
// 建立父列佈局並依序 inflate 三個子項目與分隔線
final LinearLayout linearLayout = new LinearLayout(this);
View.inflate(this, R.layout.layout_line_vertical, linearLayout);
View.inflate(this, R.layout.layout_department, linearLayout);
View.inflate(this, R.layout.layout_line_vertical, linearLayout);
View.inflate(this, R.layout.layout_department, linearLayout);
View.inflate(this, R.layout.layout_line_vertical, linearLayout);
View.inflate(this, R.layout.layout_department, linearLayout);
View.inflate(this, R.layout.layout_line_vertical, linearLayout);
LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.addView(linearLayout, layoutParams);
View.inflate(this, R.layout.layout_line_horizonal, layout);
// 依索引 getChildAt 找到對應位置,設定 tag、點擊、文字與圖片
final View firstView = linearLayout.getChildAt(1);
firstView.setTag(firstCategory);
firstView.setOnClickListener(this);
((TextView) firstView.findViewById(R.id.text_title)).setText(firstCategory);
((ImageView) firstView.findViewById(R.id.image_icon)).setImageDrawable(firstDrawable);
// second、third 同理
}
}
@Override public void onClick(View v) {
// 透過佈局時設定的 tag 找出使用者點的是哪一項
final Object tag = v.getTag();
if (tag != null) {
String department = (String) tag;
Toast.makeText(this, department, 0).show();
}
}
}
這裡有兩個實作重點值得留意:一是透過 getIdentifier() 依命名規則動態查找 drawable 資源,再用 StateListDrawable 快取「預設圖」與「按下圖」兩種狀態;二是在 onClick 中透過佈局時設定的 Tag 判斷使用者究竟點了哪一項。掌握這套「資料驅動佈局」的思路,就能輕鬆應對條目數量不固定的動態界面需求。
詳解Android Preference首選項的編寫與組織
翻 Android 書籍時常看到「首選項」這個名詞,但多數書直接教你怎麼用,很少說明它從哪來、憑什麼存在。這一篇就先把概念講清楚,再動手做。 首選項到底是什麼 「首選項」
Android 自定義相機:實現手機拍照功能
系統自帶的相機在定製化需求面前往往不夠用,這時候就需要自己調用 Camera API 做一個。本文用一個完整示例演示如何實現取景預覽、自動對焦與拍照保存。 一、布局文件
刷機精靈 adb 怎麼刷機?常用指令速查
用過刷機精靈新版的人,大概都看過那個 adb 命令工具。多數人對指令行本來就陌生,非必要時並不建議走這條路,但遇到工具圖形介面搞不定的狀況,adb 往往是最後手段。以下把
從 Android 源碼到 APK:打包流程一次看懂
打包流程 Android 程式從源碼到可安裝的 APK,通常會經過資源處理、程式碼編譯、DEX 轉換、打包、對齊與簽名等步驟。 在較詳細的流程中,建置工具會先處理 An