Android Setting the left / right field does not work

This is strange, but setting the left or right margin in Java code does not 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 have a green view inside FrameLayout. When turning, I change the field of view. (my activity has android: configChanges = "orientation | screenSize")

Here are the results:

Samsung Galaxy S 3 (Android 4.1.2) (works great)

enter image description here

enter image description here

Sony Ericsson Xperia Arc S (Android 4.0.4) (it works weird!)

enter image description here

enter image description here

As you can see, the code works correctly on Android 4.1.2. And on Android 4.0.4, the left and right fields are not set, but the top field is set. Why top?

I tested emulators. All platforms> = Android 4 work fine. On Android 2.3 brands are not installed at all, even the top margin.

Does anyone know how to deal with this? How to change the margin in the code so that it works on all platforms?

+4
source share
3 answers

Sony Ericsson Xperia Arc S (Android 4.0.4) Sony LT26ii (Android 4.0.4) both do not work I have no choice but to replace RelativeLayout

+2
source

I had the same problem as mine and my solution: creating a new LayoutParams instead of getting the old one.

  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 this helps.

+1
source

When you set the fields it is like

  params.leftMargin = 50; params.rightMargin = 50; params.topMargin = 50; params.bottomMargin = 50; 

it uses pixels, not dp, which could explain why they look different on different devices. Try converting pixels to dp like this.

Convert pixels to dp

0
source

Source: https://habr.com/ru/post/1499712/


All Articles