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.) extend ViewGroup
.
The ViewGroup
class has two static inner classes: LayoutParams
and MarginLayoutParams
. And ViewGroup.MarginLayoutParams
actually extends ViewGroup.LayoutParams
.
Sometimes layout classes need extra layout information to be associated with child view. For this they define their internal static LayoutParams
class. For example, LinearLayout
has:
public class LinearLayout extends ViewGroup {
...
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
...
}
}
Same thing for RelativeLayout
:
public class RelativeLayout extends ViewGroup {
...
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
...
}
}
But LinearLayout.LayoutParams
and RelativeLayout.LayoutParams
are completely different independent classes. They store different additional information about child views.
For example, LinearLayout.LayoutParams
can associate weight
value with each view, while RelativeLayout.LayoutParams
can't. Same thing with RelativeLayout.LayoutParams
: it can associate values like above
, below
, alightWithParent
with each view. And LinearLayout.LayoutParams
simply don't have these capability.
So in general, you have to use LayoutParams
from enclosing layout to make your view correctly positioned and rendered. But note that all LayoutParams
have same parent class ViewGroup.LayoutParams
. And if you only use functionality that is defined in that class (like in your case WRAP_CONTENT
and FILL_PARENT
) you can get working code, even though wrong LayoutParams
class was used to specify layout params.