2012-04-21 167 views
0

-UPDATE-循環與setLayoutParams - 拋出ClassCastException

我已經照阿加瓦爾認爲,現在有這樣的錯誤:

04-21 11:42:01.807: E/AndroidRuntime(1456): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams 

我使用這個代碼,以動態地設置的15個按鈕的寬度。而且,你猜對了,它不起作用。該錯誤發生在for循環中,但我不確定原因。

Button[] buttons = new Button[16]; 
    buttons[0] = (Button)findViewById(R.id.root2); 
    buttons[1] = (Button)findViewById(R.id.root3); 
    /* blah blah blah */ 
    buttons[13] = (Button)findViewById(R.id.root15); 
    buttons[14] = (Button)findViewById(R.id.root16); 

    LayoutParams lp = new LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT); 

    for(int x = 0; x < 16; x ++){ 
     buttons[x].setLayoutParams(lp); 
    } 

感謝您的幫助。 (如果有人能想到更好的辦法來填補buttons[]變量,這將是非常讚賞。)

+0

你有15或16個按鈕 – 2012-04-21 11:38:49

回答

3
for(int x = 0; x < 16; x ++){ 
     buttons[x].setLayoutParams(lp); 
    } 

上述循環repaeat 16次,你有instilized只有15個按鍵或者添加一個按鈕或更改x < 15. 如果更改x < 15,則還可以更改以下

按鈕[]按鈕=新按鈕[15];

+0

謝謝你。我已經將它更改爲'x <15',現在有一個新的錯誤。你介意看看嗎?我已經更新了這個問題。 – ACarter 2012-04-21 11:48:22

+0

editted看帖子 – 2012-04-21 11:58:41

+0

我打開陣列太多不是我,但我仍然得到這個問題。感謝您的所有幫助。 – ACarter 2012-04-21 12:02:43

1

我一直在使用這個固定:

LayoutParams lp = new LinearLayout.LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT); 

    for(int x = 0; x < 15; x ++){ 
     buttons[x].setLayoutParams(lp); 
    } 

LinearLayout獲取LayoutParams

相關問題