I change the size of RelativeLayout right in the code

RelativeLayout fragmentContainer = (RelativeLayout) mainActivity.findViewById(R.id.fragmentContainer); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(0,56,0,0); fragmentContainer.setLayoutParams(layoutParams); 

As written in the documentation,

Sets the margins, in pixels.

How do I make the indent from above equal 56 ( android:actionBarSize ) in dp

  • one
    Look here PS did not send a comment because there were not enough balls - Dmitry

2 answers 2

 float dp = mainActivity.getResources().getDisplayMetrics().density; int margin = 56; int totalMargin =(int) dp * margin; layoutParams.setMargins(0,totalMargin,0,0); fragmentContainer.setLayoutParams(layoutParams); 

PS Thanks @Dmitry

    You can take from resources, then the system itself will translate into pixels:

     int totalMargin = (int) getResources().getDimension(R.dimen.total_margin); layoutParams.setMargins(0,totalMargin,0,0); fragmentContainer.setLayoutParams(layoutParams); 

    in the resources file dimens.xml

     <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="total_margin">56dp</dimen> </resources>