I have the following layout in main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="125dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:padding="5dp"
android:background="#FFFF00">
<View
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="290dp"
android:background="#FF0000" />
</FrameLayout>
</FrameLayout>
And the following code in MainActivity.java:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = findViewById(R.id.placeholder);
MarginLayoutParams mlParams = (ViewGroup.MarginLayoutParams)view.getLayoutParams();
mlParams.topMargin = 50;
view.setLayoutParams(mlParams);
}
}
The margin will be applied to the child’s view but it won’t affect the parent’s view size at all. I could “fix” this issue with the following line:
((View)view.getParent()).getLayoutParams().height += 50;
But how can I do that without explicitly changing the parent’s `height? Is this possible or it doesn’t make much sense?
If you want the inner FrameLayout to grow with the child size, you have to set it’s height to
wrap_content.If you give it a fixed height, as you did here, nothing will change that. It will keep the fixed size, no matter to what size/margins you adjust the children. Which means you have to adjust the parent size manually as well if you want to avoid wrap_content (as you already said).
And just by the way: The root viewgroup, where your content gets placed is always a FrameLayout. Which means that you create a FrameLayout in a FrameLayout in a FrameLayout. 🙂 That might deepen the view hierachy unneccessary, depending on if you got other views in here. A deep hierachy is bad for performance, keep it flat if you can. Maybe have a look at the
<merge />tag.