Working with the XML file was easy as I could specify the parameters as
<android:layout_width="fill_parent" android:layout_height="wrap_content">
But I am confused while specifying it through code. For each view I specify the parameters using
view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
I see that I have an option of specifying it as relative layout, frame layout etc.
As of now I am using linear layout for all views such as images, text and also gridview. Should the view parameters be defined based on the layout of the parent element? Or is it OK to specify it as linear layout even if the view is a child of, say, a framelayout? Sorry, but I couldn’t find out the difference.
All layout classes (
LinearLayout,RelativeLayout, etc.) extendViewGroup.The
ViewGroupclass has two static inner classes:LayoutParamsandMarginLayoutParams. AndViewGroup.MarginLayoutParamsactually extendsViewGroup.LayoutParams.Sometimes layout classes need extra layout information to be associated with child view. For this they define their internal static
LayoutParamsclass. For example,LinearLayouthas:Same thing for
RelativeLayout:But
LinearLayout.LayoutParamsandRelativeLayout.LayoutParamsare completely different independent classes. They store different additional information about child views.For example,
LinearLayout.LayoutParamscan associateweightvalue with each view, whileRelativeLayout.LayoutParamscan’t. Same thing withRelativeLayout.LayoutParams: it can associate values likeabove,below,alightWithParentwith each view. AndLinearLayout.LayoutParamssimply don’t have these capability.So in general, you have to use
LayoutParamsfrom enclosing layout to make your view correctly positioned and rendered. But note that allLayoutParamshave same parent classViewGroup.LayoutParams. And if you only use functionality that is defined in that class (like in your caseWRAP_CONTENTandFILL_PARENT) you can get working code, even though wrongLayoutParamsclass was used to specify layout params.