Anil Singh
Anil Singh

Reputation: 65

androidx.gridlayout.widget.GridLayout cannot be cast to android.widget.GridLayout

I am getting error

"Caused by: java.lang.ClassCastException: androidx.gridlayout.widget.GridLayout cannot be cast to android.widget.GridLayout", in mainActivity.java

 GridLayout mygridLayout = findViewById(R.id.gridLayout);

 for(int i=0; i<mygridLayout.getChildCount(); i++)
 {
     ((ImageView) mygridLayout.getChildAt(i)).setImageResource(0);
 }

Upvotes: 5

Views: 5833

Answers (5)

Ashok Kumar
Ashok Kumar

Reputation: 1

For this, we need to import "androidx.gridlayout.widget.GridLayout;" instead of "android.widget.GridLayout;".

Upvotes: 0

Avinabh chambial
Avinabh chambial

Reputation: 199

Change

import android.widget.gridLayout 

to

import androidx.gridlayout.widget.GridLayout;

and your code will work

Upvotes: 16

Boris Goziker
Boris Goziker

Reputation: 1

You should change your code to this:

androidx.gridlayout.widget.GridLayout mygridLayout = (androidx.gridlayout.widget.GridLayout) findViewById(R.id.gridLayout);

Upvotes: 0

Ziad JD
Ziad JD

Reputation: 61

Use this in the code it will work.

androidx.gridlayout.widget.GridLayout mygridLayout = findViewById(R.id.gridLayout);

for(int i=0; i<mygridLayout.getChildCount(); i++){
 ((ImageView) mygridLayout.getChildAt(i)).setImageResource(0);
} 

Upvotes: 6

David Wasser
David Wasser

Reputation: 95656

You are using GridLayout from AndroidX package in your layout.xml and you are importing Gridlayout from package android.widget in your source code. Use one or the other and make them consistent.

Upvotes: 0

Related Questions