0
我想通過表格佈局來檢查按鈕的條件,然後用setText
來改變它們。 我遇到的問題是,我得到ClassCastException
。 我看到它說我無法將按鈕投射到ViewGroup,但我不知道爲什麼會發生這種情況,我不想在此時改變任何內容。 我相信這條線(69)是問題所在,但肯定爲什麼。AppCompatButton不能轉換爲android.view.ViewGroup
View view = ((ViewGroup) ((ViewGroup) tableLayoutChild).getChildAt(i));
代碼:
public Button aiPlayerPick() {
Button btn = null;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
View tableLayoutChild = tableLayout.getChildAt(rowIndex);
if (tableLayoutChild instanceof TableRow) {
for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
View view = ((ViewGroup) ((ViewGroup) tableLayoutChild).getChildAt(i));
if (view instanceof Button && view.getTag() == aiPickedButton) {
View btn_v = view.findViewWithTag(aiPickedButton);
System.out.println("Button: " + btn_v);
//btn = (Button) findViewById(R.id.btn_v);
break;
} else {
i++;
}
}
}
}
return btn;
}
錯誤:
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatButton cannot be cast to android.view.ViewGroup
at com.example.richardcurteis.connect3.MainActivity.aiPlayerPick(MainActivity.java:69)
at com.example.richardcurteis.connect3.MainActivity.playerClick(MainActivity.java:49)
at com.example.richardcurteis.connect3.MainActivity.humanPlayerTurn(MainActivity.java:34)
at com.example.richardcurteis.connect3.MainActivity.receiveClick(MainActivity.java:29)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
完美。隊友的歡呼聲 –