【转】 异常:java.lang.ClassCastException: android.view.* cannot be cast to android.view.*

Original address: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1117/1991.html

There was a problem when using LayoutParams today. I used it like this:

When the gridview is initialized, a header is added to the gridview (I use a third-party GridView to add headers):

  1. headerView = new View(getActivity());
  2. LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, (int)300);
  3. headerView.setLayoutParams(params);
  4. mGridView.addHeaderView(headerView);

Then when the program is executed somewhere, I hope setLayoutParamsto change the height through, so I do:

  1. LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 500);
  2. headerView.setLayoutParams(params);

The point is that both of them LayoutParams are ViewGroup LayoutParams , and then the following error occurs as soon as they are executed:

 

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams

As with many exceptions in Android, you are often confused about the original meaning of the exception. The exception says that the two are of different types LayoutParams , but they are all ViewGroup LayoutParams. And I am sure that ViewGroup can LayoutParamsbe used in the header of the GridView, because I will not report an error if I do not execute the second code above (again, I am using a third-party GridView to add headers).

 

Then I searched for the answer on stackoverflow. Although I didn't find a satisfactory one, some personal answer woke me up. Did you create a LayoutParamsnew relationship in the second code ? So I changed the second piece of code to:

  1. LayoutParams params = headerView.getLayoutParams();
  2. params.height = 500;

In fact, it is not to create a new one LayoutParams, but to obtain it directly from the original View LayoutParams.

After the modification, there is no abnormality in the operation result.

It seems that when a View already exists LayoutParams, a newly created one cannot be added again LayoutParams.

 

Finally, this is only my understanding based on the actual situation, and does not ensure that my analysis is correct, but according to my understanding, the problem is indeed solved.

Guess you like

Origin blog.csdn.net/zhengjian1996/article/details/112936976