问题
i'm making chat app. I want to put timestamp besides the chat bubble. The messages will be aligned left (for received) and right (for sent).
So, I'm looking for a way to change toLeftOf
to toRightOf
. For now, it looks like this:

Here's my XML code for each message (I have ArrayAdapter
that handle this)
<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>
I googling around and found this, but doesn't work:
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);
Any solution? Thanks
回答1:
Rewrite
Remove the attribute layout_toRightOf
from the current TextView, then create two different LayoutParams: one for toRightOf
and one for toLeftOf
. You can switch the parameters depending on your needs.
An alternative is to use a custom adapter with two layouts. This approach should be faster since you aren't re-arranging the layout at run-time but maintaining two separate lists of "Reply" and "Send" layouts in the view recycler.
(As a note, API 17 introduced removeRule() but this won't help just yet.)
回答2:
Try this to remove the toRightOf and toLeftOf property from any view.I am removing these properties from 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);
回答3:
Please used below Code.
RelativeLayout wrapper = (RelativeLayout) findViewById(R.id.wrapper);
if(isReceivedMessage){
wrapper.setGravity(Gravity.RIGHT);
}
else{
wrapper.setGravity(Gravity.LEFT);
}
来源:https://stackoverflow.com/questions/13488013/programmatically-change-relativelayout-torightof-to-toleftof