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

Joh*_*ard 20 android dynamic margins

我有一个简单的看法:

<?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>
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

这是它的样子:

在此输入图像描述

主布局中的容器是LinearLayout,它是Horizo​​ntalScrollView的子级.任何见解都表示赞赏.

Sub*_*sed 47

动态添加视图时,不应View使用null ViewGroup父级对其进行充气.所以,换句话说,你应该使用inflater.inflate(R.layout.test, linearLayout, false);.在确定要生成的布局参数类型时使用父级.传递父容器(在本例中为线性布局),以便从XML中正确实例化ViewGroup.MarginLayoutParams.

  • @JohnWard实际上,如果您对最后一个布尔参数使用“ inflater.inflate(R.layout.test,linearLayout,false)”,实际上您仍然需要addView。 (3认同)

小智 5

发生这种情况是因为您需要动态地为布局提供“边距”。您可以通过创建“ 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);
Run Code Online (Sandbox Code Playgroud)

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

ll.addView(okButton, layoutParams);
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。