AppCompatButton不能强制转换为android.view.ViewGroup



我正试图在表格布局中循环,检查按钮是否有条件,然后用setText更改它们。我现在遇到的问题是在那之前我得到了ClassCastException。我看到它说我不能向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);

相关内容

最新更新