如何通过java代码更改android:layout_alignParentRight运行时

问题描述:

我有聊天列表视图,其中发件人名称应该左对齐,接收者的回复应该在右侧,然后反之,当接收者成为发件人时。如何通过java代码更改android:layout_alignParentRight运行时

这里是我的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" /> 

现在在运行时我想改变的TextView的layout_alignParentRight值。有可能吗?

尝试:

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

谢谢appserv,这是一个伎俩对于我..应用Align_parent后,它不能在一个文本视图,由于layout_width =“fill_parent”转换为“wrap_content”后它工作......只是一个常用的在这里使用:) – Zoombie 2012-03-28 12:32:13

肯定是可能的,你可以用这个东西: -

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


rlp.addRule(RelativeLayout.ALIGN_RIGHT, 
        textviewid); 

形式的代码你得到一些裁判..

使用此代码

RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
          LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
     _params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
     apps_layout.setLayoutParams(_params);