-1

I am new to android development. So, I'm having hard time on how to do this. My Activity Screen(Preferably Relative Layout) needs to have a bottom margin(say 1 dp) with the display screen. How can I do this programatically? Thanks

shamim Emon
  • 29
  • 1
  • 8

1 Answers1

0

You can add a bottom margin by using android:layout_marginBottom="1dp".

To do it programmatically...

// Setup your RelativeLayout
RelativeLayout yourLayout = (RelativeLayout) findViewById(R.id.your_relative_layout);

// Set the margin
MarginLayoutParams params = (MarginLayoutParams) yourLayout.getLayoutParams();
yourLayout.bottomMargin = 1; // This sets the bottom margin to 1px
yourLayout.setLayoutParams(params);

If you want to set it in pixels, you replace yourLayout.bottomMargin = 1; with:

yourLayout.bottomMargin = dpToPixels(1);

And add the following method:

private int dpToPixels(int dps) {
    if (dps == 0) {
        return 0;
    }
    final float scale = getResources().getDisplayMetrics().density;
    return (int) (dps * scale + 0.5f);
}
Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125