以编程方式在 RelativeLayout 中设置视图边距没有任何影响

Setting margin on view in RelativeLayout programmatically doesn't have any affect

在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);
    }
}

要在 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);
    }