问题
This is strange, but setting left or right margin in Java code doesn't work on some devices/platforms.
Here is the code. Simple xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
>
<View
android:id="@+id/myView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:background="#00ff00" />
</FrameLayout>
Java:
@Override
public void onConfigurationChanged (Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)findViewById(R.id.myView).getLayoutParams();
params.leftMargin = 50;
params.rightMargin = 50;
params.topMargin = 50;
params.bottomMargin = 50;
findViewById(R.id.myView).requestLayout();
}
}
So I've got a green view inside FrameLayout. On rotate I change margin of View. (my activity has android:configChanges="orientation|screenSize")
Here is results:
Samsung Galaxy S 3 (Android 4.1.2) (works fine)
Sony Ericsson Xperia Arc S (Android 4.0.4) (works strange!)
As you can see on the code works properly on Android 4.1.2. And on Android 4.0.4 left and right margins are not set, but top margin is set. Why top?
I've tested on emulators. All platforms >= Android 4 works fine. On Android 2.3 margins are not set at all, even top margin.
Does anyone know how to deal with it? How to change margin in code so it would work on all platforms?
回答1:
Sony Ericsson Xperia Arc S (Android 4.0.4) Sony LT26ii (Android 4.0.4) both doesn't work I have no choice but replace it with RelativeLayout
回答2:
When you set the margins likes this
params.leftMargin = 50;
params.rightMargin = 50;
params.topMargin = 50;
params.bottomMargin = 50;
it uses pixels not dp which could explain why it looks different on different devices try converting your pixels to dp like this
Converting pixels to dp
回答3:
I had same problem as you have and my solution is: creating a new LayoutParams instead of getting the old.
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(WIDTH, HEIGHT, Gravity.TOP);
params.setMargins(50,50,50,50);
findViewById(R.id.myView).setLayoutParams(params);
}
WIDTH and HEIGHT: You can also set android.widget.FrameLayout.LayoutParams.MATCH_PARENT, or android.widget.FrameLayout.LayoutParams.WRAP_CONTENT
Hope it can help.
来源:https://stackoverflow.com/questions/18522126/android-setting-left-right-margin-doesnt-work