简体   繁体   English

Android:如何以编程方式设置视图的边距?

[英]Android: how can I set margins of the view programmatically?

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-->
/>

Yes, you can set margin programatically using是的,您可以使用编程方式设置margin

    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));
    }
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.注意:我添加的边距以 px 为单位,您可能需要以编程方式将其转换为 dp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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