android 动态插入视图时边距不起作用

android margins not working when dynamically inserting views

我有一个简单的看法:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/contact_selected"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="5dp"
    android:orientation="horizontal"
    android:padding="3dp">
    <TextView
        android:id="@+id/txt_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Billy Bob"
        />
</LinearLayout>

当我将 LinearLayout 标记静态复制到我的主 activity 布局中时,边距符合预期。但是,当我将视图动态添加到主 activity 布局中时,边距将被忽略。这是我插入视图的方式

LayoutInflater inflater = (LayoutInflater)
        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test, null);
TextView txt_title = (TextView)view.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #1");
llayout.addView(view, llayout.getChildCount()-1);

View view2 = inflater.inflate(R.layout.test, null);
txt_title = (TextView)view2.findViewById(R.id.txt_title);
txt_title.setText("Dynamic #2");
llayout.addView(view2, llayout.getChildCount()-1);

这是它的样子:

主布局中的容器是 LinearLayout,它是 Horizo​​ntalScrollView 的子项。感谢任何见解。

动态添加视图时,不应使用 null ViewGroup 父级扩充 View。所以,换句话说,你应该使用 inflater.inflate(R.layout.test, linearLayout, false);。在确定要生成的布局参数类型时使用父级。传递您的父容器(在这种情况下,您的线性布局),因此它正确地从您的 XML.

实例化 ViewGroup.MarginLayoutParams

发生这种情况是因为您需要动态地为布局提供“边距”。您可以通过创建“LayoutPrams”的对象来完成此操作,如下所示:-

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);

在这里,您可以将 LayoutParams 设置为线性布局:

ll.addView(okButton, layoutParams);

希望对您有所帮助。

首先,您必须获得显示密度。 相关文档是 https://developer.android.com/reference/android/util/DisplayMetrics.html

并获取您想要设置边距视图的 ID。 对于我来说,

layout_login_box = (ConstraintLayout)findViewById(R.id.login_layout_box);

float density = getResources().getDisplayMetrics().density;

ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams)layout_login_box.getLayoutParams();
params.setMargins((int) (24  * density),0,(int) (24  * density),(int) (16  * density));
layout_login_box.setLayoutParams(params);

此外,您可以将 ConstraintLayout 更改为您自己的视图。