以编程方式在RelativeLayout中设置视图边距不会产生任何影响

时间:2017-03-31 06:41:31

标签: java android android-layout relativelayout margins

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

1 个答案:

答案 0 :(得分: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);
    }