我試圖爲每一年開始使用我的應用程序以來創建一個按鈕。所以我的XML文檔中我有動態添加按鈕到已存在的按鈕陣列
<HorizontalScrollView
android:id="@+id/yearScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/white"
android:layout_gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/currentYear"
android:tag="01"
android:text="2015"
android:paddingLeft="8.0dip"
android:paddingRight="8.0dip"
android:height="24dp"
android:textSize="18sp"
android:textColor="#333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/white"
>
</Button>
</LinearLayout>
</HorizontalScrollView>
然後,我有以下代碼
private List<Button> yearButtons;
private static final int[] YEAR_BUTTON_IDS = {
R.id.currentYear,
};
然後,我必須找出它是哪一年,並覆蓋我的當前按鈕
int firstYear = Integer.parseInt(year);
yearButtons.get(0).setText(String.valueOf(CurrentYear));
然後在我的init類我證實了按鈕,我知道我不需要一個循環只有一個按鈕,但留下這樣就與月份按鈕的工作方式一致
for(int id : YEAR_BUTTON_IDS) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
yearButtons.add(button);
}
然後,我有一些邏輯來找出第一年,他們就開始叫yearsOfTransactions
然後,我有以下的循環,我試圖創建按鈕
for (int i =0; i< yearsOfTransactions; i++){
int yearToAdd = CurrentYear-i-1;
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
}
但是這是行不通的。
感謝您的幫助
不工作的手段?你需要添加它在你的線性佈局..然後它會變得可見..! –
我建議你不要把'int []'作爲'Arraylist'的id。因爲在創建一次後你不能修改數組大小.. !! –