以编程方式将RelativeLayout toRightOf更改为toLeftOf

hrs*_*ono 8 android relativelayout

我正在聊天应用程序.我想把时间戳放在聊天泡泡旁边.消息将左对齐(已接收)和右(已发送).

所以,我正在寻找一种方法来改变toLeftOftoRightOf.现在,它看起来像这样:

时间戳错误地对齐

这是我的每条消息的XML代码(我有ArrayAdapter处理这个)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/wrapper"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/bubble"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff" />

        <TextView
            android:id="@+id/timeStamp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/bubble" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我在Google上搜索并找到了这个,但是不起作用:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
     RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(isReceivedMessage){
    params.addRule(RelativeLayout.RIGHT_OF, R.id.bubble);
}
else{
    params.addRule(RelativeLayout.LEFT_OF, R.id.bubble);
}
timeStampTextView.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

有解决方案吗 谢谢

Dee*_*rma 11

尝试从任何视图中删除toRightOftoLeftOf属性.我将从textview中删除这些属性.

    TextView header2=(TextView) findViewById(R.id.text_view_header_shoppinglist);
        RelativeLayout.LayoutParams mLayoutParams2=(RelativeLayout.LayoutParams)header2.getLayoutParams();
        mLayoutParams2.addRule(RelativeLayout.LEFT_OF,0);
        mLayoutParams2.addRule(RelativeLayout.RIGHT_OF,0);
Run Code Online (Sandbox Code Playgroud)


Sam*_*Sam 2

重写从当前 TextView 中
删除该属性,然后创建两个不同的 LayoutParams:一个 for ,一个 for 。您可以根据需要切换参数。layout_toRightOftoRightOftoLeftOf

另一种方法是使用具有两种布局的自定义适配器。这种方法应该更快,因为您不是在运行时重新排列布局,而是在视图回收器中维护两个单独的“回复”和“发送”布局列表。

(请注意,API 17 已引入removeRule(),但这还没有帮助。)