gpt4 book ai didi

java - AppCompatButton 无法转换为 android.view.ViewGroup

转载 作者:行者123 更新时间:2023-12-01 10:37:14 26 4
gpt4 key购买 nike

我试图循环遍历表格布局以检查按钮的条件,然后使用 setText 更改它们。我遇到的问题是在我收到 ClassCastException 之前。我看到它说我无法将 Button 转换到 ViewGroup,但我不确定为什么会发生这种情况,我当时并没有尝试更改任何内容。我相信这一行(69)是问题所在,但不确定为什么。

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)

最佳答案

即使您存储的是 View 类型的变量,使用强制转换 (ViewGroup) 也会在存储之前强制进行强制转换。您正在获取 TableRow 的子级并将其转换为 ViewGroup,但其父级实际上是 View,因此失败。

您不需要第二次转换,因为 getChildAt() 返回 View:

View view = ((ViewGroup) tableLayoutChild).getChildAt(i);

关于java - AppCompatButton 无法转换为 android.view.ViewGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com