可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
My layout structure is like this
LinearLayout FrameLayout ImageView ImageView FrameLayout TextView LinearLayout
I have set margin's for the two ImageView which are inside FrameLayout. But FrameLayout margins are discarded and it always set's the Image to top left corner. If i change from FrameLayout to LinearLayout the margin's work properly. How to handle this ?
回答1:
I had the same issue myself and noticed that setting the layout_
margins does not work until you also set your ImageView's layout gravity i.e. android:layout_gravity="top"
in the XML resource file, or from code: FrameLayout.LayoutParams.gravity = Gravity.TOP;
.
回答2:
To make it more clear why. The FrameLayout.onLayout() call contains this (in api v2.3.4 at least):
// for each child final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int gravity = lp.gravity; if (gravity != -1) { // handle all margin related stuff
So if gravity is -1, there will be no margin calculation. And the thing is, gravity in FrameLayout.LayoutParams is defined by:
gravity = a.getInt(com.android.internal.R.styleable.FrameLayout_Layout_layout_gravity, -1);
So if gravity is not set, there will be no margin calculation.
回答3:
add your xml this attribute and re run
android:layout_gravity="top"
everything is Ok!
and you dont set new layout params like this;
FrameLayout.LayoutParams llp = new FrameLayout.LayoutParams(WallpapersActivity.ScreenWidth/2, layH);
use like this:
FrameLayout.LayoutParams llp = (LayoutParams) myFrameLay.getLayoutParams(); llp.height = 100; llp.width = 100; myFrameLay.setLayoutParams(llp);
回答4:
Taken from the FrameLayout docs (link)
The size of the frame layout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
This seems to describe the fact that it'll strip margins out. Like boulder mentioned, you could try switching to padding as it can be used to produce a similar effect if done properly.
Out of curiosity, you mentioned that it does work fine when using a LinearLayout
container, why the choice of FrameLayout?
回答5:
Have you tried android:layout_gravity ? Try using android:padding in you ImageViews instead of android:layout_margin. AFAIK margins doesn't work properly on Frame layout. I even had to write custom layout for that purpose once. BTW, how do you want allign you ImageViews?
回答6:
try setCropToPadding(true) to ImageView ,this should be helped!
回答7:
you have to set your ImageView's layout gravity top i.e. android:layout_gravity="top" in the XML resource file, or from code: FrameLayout.LayoutParams.gravity = Gravity.TOP