AppCompatButton 无法转换为 android.view.ViewGroup

AppCompatButton cannot be cast to android.view.ViewGroup

我正在尝试遍历 table 布局来检查按钮的条件,然后用 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() returns View:

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