如何通过Java代码在运行时更改android:layout_alignParentRight?

4

我有一个聊天列表视图,在这个列表里发送者的名字应该是左对齐的,接收者的回复应该在右边,当接收者成为发送者时,应该反过来。

这是我的xml文件:

<?xml version="1.0" encoding="utf-8"?>

<TextView android:id="@+id/chatmessagename"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true"
    android:textSize="16sp" android:textStyle="bold"
    android:paddingBottom="1dp" />
<TextView android:id="@+id/chatmessagedate"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"    
    android:autoLink="none" />
<TextView android:id="@+id/chatmessagetext"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@id/chatmessagename"
    android:autoLink="all" />

现在我想在运行时更改文本视图的layout_alignParentRight值。这是可能的吗?

3个回答

13

尝试:

... 
RelativeLayout.LayoutParams layoutParams =(RelativeLayout.LayoutParams)yourView.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_.....); //ALIGN_PARENT_RIGHT / LEFT etc.
yourView.setLayoutParams(params);
... 

1
谢谢Appserv,这对我很有帮助。在应用Align_parent后,它在一个textview上没有起作用,由于layout_width="fill_parent"。将其转换为'wrap_content'后,它就可以工作了...这里只是需要一些常识 :) - Zoombie

1

是的,这是可能的,你可以使用以下内容:

            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
                android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);


rlp.addRule(RelativeLayout.ALIGN_RIGHT,
                    textviewid);

从这段代码中,你可以得到一些引用。


0
请使用这段代码。
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
                          LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        _params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        apps_layout.setLayoutParams(_params);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接