Android Studio 開發使用 Java 創建 UI 控件
首先需要爲生成控件的 Activity 設置一個 ID,詳情看代碼註釋:
linearLayout = (LinearLayout)findViewById(R.id.linearLayout); // 生成控件的 Activity
Button btnLesson = new Button(this); // 創建一個新的Button對象
btnLesson.setId(id); // 設置對象的id
btnLesson.setText(text); // 設置對象顯示的值
btnLesson.setOnClickListener(new btnListener(btnLesson)); // 給按鈕添加監聽事件
linearLayout.addView(btnLesson); // 將 Button 對象添加到 LinearLayout 中
這裏,在 id 爲 LinearLayout 的 Activity 中生成了一個 Button 控件,並且爲其創建了一個 btnListener() 的監聽函數:
class btnListener implements View.OnClickListener { // 創建一個按鈕監聽類
private Button btn; // 定義一個 Button 類型的變量
private btnListener(Button btn) { // 一個構造方法, 將 Button 對象做爲參數
this.btn = btn; // 將引用變量傳遞給實體變量
}
public void onClick(View view) {
// 按鈕點擊事件,這裏有兩個數據可以使用:bth、view
}
}