相对布局忽略 setMargin()

2024-01-10

我正在尝试嵌套一个RelativeLayout里面的一个LinearLayout,并给出RelativeLayout将其边缘与边缘的边缘隔开的边距LinearLayout。到目前为止我有这个:

LayoutInflater.from(context).inflate(R.layout.conversation_view_layout, this, true);

this.setLayoutParams(new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
int tbm = AllConversationsActivity.topAndBottomMargin;
int lrm = AllConversationsActivity.leftAndRightMargin;
((MarginLayoutParams) this.getLayoutParams()).setMargins(lrm, tbm, lrm, tbm);
this.requestLayout();

如果我正确地读取 API,应该将relativelayout 的边距设置为指定的数字。它根本没有这样做,而似乎只是忽略了setMargins()完全。

另外,这是我的 xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">

<ImageView 
    android:id="@+id/conversation_picture"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"/>

<TextView 
    android:id="@+id/conversation_person"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@id/conversation_picture"
    android:singleLine="true"
    android:ellipsize="marquee"/>

<TextView 
    android:id="@+id/conversation_length"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"/>

<TextView 
    android:id="@+id/conversation_first_line"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@id/conversation_picture"
    android:layout_alignParentLeft="true"
    android:singleLine="true"
    android:ellipsize="end"/>

<TextView 
    android:id="@+id/conversation_last_time"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@id/conversation_first_line"
    android:layout_alignParentLeft="true"
    android:singleLine="true"
    android:ellipsize="marquee"/>

我有点怀疑这些观点正在迫使RelativeLayout当它们进行对齐调用时,边到父边。 有人知道必须做什么才能设置这些边距吗?或者也许有更好的方法来完全做到这一点? 赞赏。


Edit:

您正在使用 MarginLayoutParams 而不是 LinearLayoutParams。 注意:如果在布局容器上设置 LayoutParams,则需要使用父级的类型。

因此,如果您有一个包含RelativeLayout的LinearLayout,则需要在RelativeLayout上设置LinearLayout.LayoutParams。

// NOT WORKING: LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
int tbm = AllConversationsActivity.topAndBottomMargin;
int lrm = AllConversationsActivity.leftAndRightMargin;
params.setMargins(tbm, lrm, tbm, lrm);
setLayoutParams(params);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

相对布局忽略 setMargin() 的相关文章

随机推荐