【问题标题】:Setting margin on view in RelativeLayout programmatically doesn't have any affect以编程方式在 RelativeLayout 中设置视图边距没有任何影响
【发布时间】:2017-03-31 06:41:31
【问题描述】:

在 Android 中,我在 Java 代码中创建了一个 ImageView,并在将其添加到主布局(RelativeLayout)之前设置了它的布局参数:宽度、高度和上边距。宽度和高度已成功应用,但边距对图像视图位置没有任何影响。实际的上边距保持为 0。

如何将上边距应用于视图?代码如下。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initClouds();
    }

    private void initClouds() {
        addCloud(R.drawable.cloud1, R.dimen.cloud1_top_margin);
        addCloud(R.drawable.cloud2, R.dimen.cloud2_top_margin);
    }

    private void addCloud(int imageResId, int topMarginResId) {
        RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);

        ImageView cloud = new ImageView(this);
        int height = (int) getResources().getDimension(R.dimen.cloud_height);
        int width = (int) getResources().getDimension(R.dimen.cloud_width);
        ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width, height);
        params.topMargin = (int) getResources().getDimension(topMarginResId);
        cloud.setImageResource(imageResId);
        mainLayout.addView(cloud, params);
    }
}

【问题讨论】:

  • 你确定getResources().getDimension(topMarginResId)返回的不是0吗?
  • 是的,它返回非零值。我已经记录了结果并得到了正确的值:topMargin=120 topMargin=30

标签: java android android-layout android-relativelayout margins


【解决方案1】:

要在 RelativeLayout 中设置视图的边距,您应该使用 RelativeLayout.LayoutParams 。像这样更改您的代码,

private void addCloud(int imageResId, int topMarginResId) {
        RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);

        ImageView cloud = new ImageView(this);
        int height = (int) getResources().getDimension(R.dimen.cloud_height);
        int width = (int) getResources().getDimension(R.dimen.cloud_width);
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(width, height);
        param.topMargin = (int) getResources().getDimension(topMarginResId);

        cloud.setImageResource(imageResId);
        mainLayout.addView(cloud, param);
    }

【讨论】:

  • 你能发布你的屏幕截图吗?
  • 我尝试了其他布局中的 LayoutParams:LinearLayout。但是正确的 RelativeLayout.LayoutParams 会做出很大的改变并且确实有效。
猜你喜欢
  • 2015-02-24
  • 2011-04-08
  • 2011-01-29
  • 2019-10-19
  • 2023-04-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2012-05-16
相关资源
最近更新 更多