繁体   English   中英

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

[英]AppCompatButton cannot be cast to android.view.ViewGroup

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM