0

Hi I am developing android application. I am creating view programatically.In my layout I have relative layout as root element. I tried to set margin to my root relative layout. But I am not able to do that. I tried this in following way:

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout relativeLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);

        rlp.setMargins(100,100,100,100);
        relativeLayout.setLayoutParams(rlp);
        relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent3));

        setContentView(relativeLayout);
    }
}

above code add relative layout to my activity. But not considering margins. Need some help. Thank you.

nilkash
  • 7,408
  • 32
  • 99
  • 176

2 Answers2

1

It won't work the way you're trying because that's how the Framework works. The root view always takes the whole space, no margins.

What you can do instead is:

  • use padding instead (if your layout allows it)
  • create a FrameLayout, create the RelativeLayout, create a FrameLayout.LayoutParams, set the margins on the layout params, set the layout params into the RelativeLayout, add the RelativeLayout into the FrameLayout and add setContentView(frameLayout)
Budius
  • 39,391
  • 16
  • 102
  • 144
0

LayoutParams should be applied on children not the parent itself. The root view for an Activity is not a RelativeLayout. First of all if you print out findViewById(android.R.id.content).getClass().getName() you will find that the root view is a android.support.v7.widget.ContentFrameLayout which I assume(from the name) is a FrameLayout on support-v7 (AppcompatActivity). If you look android support library sources here you will see that it is indeed a FrameLayout. My idea is that we should try to give our RelativeLayout FrameLayout.LayoutParams like so

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
relativeLayout.setLayoutParams(params);
Peter Chaula
  • 3,456
  • 2
  • 28
  • 32