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):
- headerView = new View(getActivity());
- LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, (int)300);
- headerView.setLayoutParams(params);
- mGridView.addHeaderView(headerView);
Then when the program is executed somewhere, I hope setLayoutParams
to change the height through, so I do:
- LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 500);
- 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 LayoutParams
be 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 LayoutParams
new relationship in the second code ? So I changed the second piece of code to:
- LayoutParams params = headerView.getLayoutParams();
- 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.