2012-04-21 73 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

相关问题