3therk1ll
3therk1ll

Reputation: 2441

AppCompatButton cannot be cast to android.view.ViewGroup

I am trying to loops through table layout to check the button for a condition and then to change them with setText. The problem I am having is before that I am getting a ClassCastException. I see that it says I can't cast a Button to a ViewGroup, but I'm not sure why that it is happening, I am not trying to change anything at that point. I believe this line (69), is the problem, but nty sure why.

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

Code:

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;
    }

Error:

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)

Upvotes: 0

Views: 1675

Answers (1)

Dan Lew
Dan Lew

Reputation: 87420

Even though you're storing a variable of type View, using the cast (ViewGroup) forces a cast to happen before being stored. You're taking the child of the TableRow and casting it to ViewGroup, but its parent is actually View so it fails.

You don't need the second cast, since getChildAt() returns View:

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

Upvotes: 1

Related Questions