-3

here is the view, which I want to give bottom margin programmatically

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"<!--this thing want to do via java/kotlin code-->
/>
Mohd Qasim
  • 896
  • 9
  • 20
  • 7
    Possible duplicate of [In Android, how do I set margins in dp programmatically?](https://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically) – Gautam Chibde Mar 09 '18 at 06:36

2 Answers2

2

Yes, you can set margin programatically using

    ProgressBar view;
    RelativeLayout.LayoutParams params = view.getLayoutParams();
    int marginInPx = convertDpToPx(20);
    params.setMargins(0,0,0,marginInPx);
    view.setLayoutParams(params);

    private int convertDpToPx(float dp){
       DisplayMetrics metrics = getResources().getDisplayMetrics();
       return (int)((int)dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
0
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 0, 20);
progressBar.setLayoutParams(layoutParams);

Note: The margin I added is in px you may need to convert it into dp programmatically.

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440