Mykhaylo Kopytonenko
Mykhaylo Kopytonenko

Reputation: 953

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

In Android, I create an ImageView in the Java code and set its layout parameters: width, height and top margin before adding it to the main layout (RelativeLayout). The width and height are applied successfully, but the margin doesn't have any affect on the image view position. The actual top margin stays 0.

How to apply the top margin to views? The code is below.

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

Upvotes: 0

Views: 502

Answers (1)

Krish
Krish

Reputation: 3885

For setting the margin for a view inside RelativeLayout you should use RelativeLayout.LayoutParams . Change your code like this ,

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

Upvotes: 1

Related Questions