Set RelativeLayout layout params programmatically - throws ClassCastException
I am inflating a RelativeLayout from XML and then attempting to programmatically sets its layout params and am receiving a ClassCastException.
Code:
profileHeader = (RelativeLayout)mInflater.inflate(R.layout.user_profile_header, null);
profileHeader.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));
throws
E/AndroidRuntime( 2963): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
E/AndroidRuntime( 2963): at android.widget.ListView.measureScrapChild(ListView.java:1119)
E/AndroidRuntime( 2963): at android.widget.ListView.measureHeightOfChildren(ListView.java:1202)
E/AndroidRuntime( 2963): at android.widget.ListView.onMeasure(ListView.java:1111)
E/AndroidRuntime( 2963): at android.view.View.measure(View.java:8222)
E/AndroidRuntime( 2963): at android.view.ViewGroup.measureChildWithMargins(V
I've seen other notes on the net to try using LinearLayout.LayoutParams but that doesnt seem to help.
If you're wondering why I am doing this at all and NOT just setting it in the XML its because I am seeing something weird w开发者_开发技巧here the layout "jumps" to a wrap/wrap. I AM setting it to fill_parent/fill_parent in the XML and on scroll the view "shrinks" to what appears to be wrap/wrap. Its really weird. Looking at the foursquared android source code I found a comment where the developer says the same thing:
"Something odd is going on with the layout parameters though. If we don't explicitly set the layout to be fill/fill after inflating, the layout jumps to a wrap/wrap layout." (FriendsActivity.java:258)
Which sounds just like my problem, hence I am trying to do the same (set layout via code), but in his case he is using LinearLayout, whereas I am using RelativeLayout.
What am I missing? Thanks in advance.
The layout params have to be of the type of the parent. So if you are creating a RelativeLayout and adding it to a ListView, the layout params must be of type ListView.LayoutParams, not RelativeLayout.LayoutParams. The correct way to do it is to call inflate this way:
inflate(R.layout.mylayout, theListView, false);
This version of inflate() will correctly inflate the layout parameters (android:layout_*) defined in XML.
If your view is in a ListView, you must use AbsListView.LayoutParams
.
See also: Unable to set margin of item in ListView using custom Adapter
精彩评论