Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

android - 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 where 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...