2013-08-29 73 views
4

這很奇怪,但在Java代碼中設置左邊距或右邊距不適用於某些設備/平臺。Android。設置左/右邊距不起作用

這是代碼。 簡單的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(); 
    } 
} 

所以我有內部的FrameLayout綠色視圖。在旋轉時,我更改視圖的邊距。 (我的活動有機器人:configChanges = 「方向|屏幕尺寸」)

這裏是結果:

三星Galaxy S 3(安卓4.1.2)(正常工作)

enter image description here

enter image description here

索尼愛立信Xperia Arc S(的Android 4.0.4)(作品怪!)

enter image description here

enter image description here

正如你所看到的代碼工作正常在Android 4.1.2。並且在Android 4.0.4上,未設置左右頁邊距,但設置了上邊距。爲什麼最高?

我已經在模擬器上測試過。所有平臺> = Android 4正常工作。 Android 2.3的利潤率根本沒有設置,甚至是最高利潤率。

有誰知道如何處理它?如何更改代碼中的保證金,以便它可以在所有平臺上使用?

回答

0

當您設置頁邊距喜歡這個

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

它使用像素不是dp的這可以解釋爲什麼它看起來在不同設備上不同的嘗試轉換您的像素與DP這樣

Converting pixels to dp

+0

感謝,但它並不重要。這不是關於DP和PX。這是關於上邊距設置(甚至由像素設置),左邊距根本沒有設置。我想知道爲什麼,並找出我可以從代碼中完成的方式。 –

+0

爲什麼你不定義2個佈局,一個是水平的,一個是垂直的,爲什麼你要用代碼來做呢? – user1634451

+0

因爲我不想重新創建我的佈局。 –

1

我有同樣的問題,你有我的解決方案是:創建一個新的LayoutParams而不是舊的。

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和HEIGHT:您還可以設置android.widget.FrameLayout.LayoutParams.MATCH_PARENT,或android.widget.FrameLayout.LayoutParams.WRAP_CONTENT

希望它可以幫助。

2

索尼愛立信Xperia Arc S(的Android 4.0.4) 索尼LT26ii(安卓4.0.4) 都不起作用 我別無選擇,只能與RelativeLayout的更換