简体   繁体   中英

How Can I Set Margin with 'dp' programmatically?

I'm trying to create design with programmatically. I'm using LayoutParams for details and I want to set Margin and I saw ... setMargins(0, 100, 0, 100) But I want to set with 'dp' like this:

<TextView
          ...
          android:layout_marginLeft="10dp"
          .../>

How can set margin with 'dp' ?

Well you got to know the parent layout first if it's RelativeLayout you'll need:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(this);

and if it is Linear,Make sure you replace Relative with Linear to get the right layoutParams.Now you can use:

layoutParams.setMargins(i1,i2,i3,i4);

all the values should be in pixel so if you need a method,it should convert dp to px for you.Feel free to use mine then:

public int dpToPx(Context context, float dp) {
    return Math.round(dp * getDisplayMetrics(context).density);
}

now just set the layoutParams to the child view:

textView.setLayoutParams(layoutParams);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM