java - 安卓。设置左/右边距不起作用

标签 java android margin

这很奇怪,但是在 Java 代码中设置左边距或右边距在某些设备/平台上不起作用。

这是代码。 简单的 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 中有一个绿色 View 。在旋转时,我更改了 View 的边距。 (我的 Activity 有 android:configChanges="orientation|screenSize")

结果如下:

三星 Galaxy S 3 (Android 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 上根本没有设置边距,甚至是顶部边距。

有人知道怎么处理吗?如何更改代码中的边距以使其适用于所有平台?

最佳答案

索尼爱立信 Xperia Arc S(安卓 4.0.4) 索尼 LT26ii (安卓 4.0.4) 两者都不起作用 没办法只能换成RelativeLayout

关于java - 安卓。设置左/右边距不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18522126/

相关文章:

android - 通过 Android 中的耳机插孔输入音频?

css - 负边距、 float 和 Firefox

java - 从文件中读取成绩

java - 链接是否应该包含 HateOAS 中的身份验证 token ?

java - 如何让Kafka消费者从特定主题分区读取Spring Boot

java - HTML5 本地存储离线缓存在 Google AppEngine 应用程序中不起作用

java - 无法完成 HttpRequest - 错误 500/403

Android App 启动时打开虚拟键盘

css 媒体查询调整 margin-top 两个 div

css - 边距顶部 :percentage; not bound to parent height?