AppCompatButton无法强制转换为android.view.ViewGroup

时间:2016-01-04 20:21:37

标签: java android classcastexception

我正在尝试遍历表格布局以检查条件的按钮,然后使用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)

1 个答案:

答案 0 :(得分:1)

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

您不需要第二次演员,因为getChildAt()会返回View

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