This seems like it should be trivial, but I can't figure out how to set the layout_gravity for a FrameLayout's child programmatically for the life of me.
There's a ton of similar questions on SO, but after trying a good 10 of them, none of the setGravity, new FrameLayout.LayoutParams, etc. solutions seem to work.
Below is a simplified version of what I'm trying to achieve.
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextureView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</FrameLayout>
However, for external reasons, I'm adding the TextureView to the FrameLayout programatically.
mCameraPreview = new CameraPreview(this, recordMode);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview_wrapper);
preview.addView(mCameraPreview);
When I try to set the layout_gravity on the mCameraPreview, it only gives me an option for gravity, which I don't want.
Is there something I'm missing here?
Run the App in Emulator, you will see Textview positioned at various position in FrameLayout Example 2: Example of A Frame Layout without using layout gravity. Here we will use a image to fill complete screen and then we will write “abhiandroid” text in center of the image.
The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored. Show activity on this post. For layout_gravity use the answer stated by "karthi". This method sets gravity to place the children inside the view.
Frame Layout should be used to hold child view, because it can be difficult to display single views at a specific area on the screen without overlapping each other. We can add multiple children to a FrameLayout and control their position by assigning gravity to each child, using the android:layout_gravity attribute.
Whereas gravity is a field in the class. Show activity on this post. I had a similar problem with programmatically setting layout_gravity on buttons in a GridLayout. The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored. Show activity on this post.
The layout_gravity
attribute lands on the FrameLayout.LayoutParams
, not on the view itself. You'll need something like:
mCameraPreview = new CameraPreview(this, recordMode);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview_wrapper);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT,
Gravity.BOTTOM);
preview.addView(mCameraPreview, params);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With