How to make textview "grow" from right?
I'd like to create a message-like UI. I'm creating a list view with two types of rows: left and right.
Each row contains one TextView. The left one is used to display the message from the sender, while the right one is used to display the message from the current user.
What I would like to do is to set the TextView in the right row to occupy certain percentage of the screen, have text aligned to the left but to grow dynamically with the content.
To clarify, here is an image of what I would like to achieve: http://dl.dropbox.com/u/2482095/wanted.png
Blue rows are "left" rows, black rows are "right" rows.
To achieve this, I have used various combinations of LinearLayout and RelativeLayout with an empty view placed to the left, and desired textView placed to the right. What I get I something like this, which is not what I want: http://dl.dropbox.com/u/2482095/notWanted1.png (text always starting at the exact point)
I have also managed to set gravity:right, which aligns text to the right, which is also not what I wanted.
Is there any way to make TextView grow with its content?
[edit] My xml file looks something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent开发者_开发问答"
android:layout_height="fill_parent"
android:padding="5dp">
<View android:id="@+id/emptyView"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView android:id="@+id/messageBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
You should set layout_width="wrap_content" on your TextView, and layout_weight="1" on your empty view. That way, the TextView should just be as wide as needed, and the extra space will be taken by your empty view.
Basically what you want is the text to be right-aligned if it fits in one line, and left-aligned otherwise.
To measure the width of the Text use the Paint.measureText()
method. So you might use something like this for your view:
Paint paint = new Paint(view.getPaint());
LayoutParams params = view.getLayoutParams();
int availableWidth = params.width - view.getPaddingLeft() - view.getPaddingRight();
int textWidth = (int) Math.ceil(paint.measureText(view.getText().toString()));
if(textWidth <= availableWidth) {
view.setGravity(Gravity.RIGHT);
}
else {
view.setGravity(Gravity.LEFT);
}
Yes, have your view (any view) wrap_content
. This will allow the view to grow as large as its parent will allow. If your parent only allows a certain amount of space for your view to take, the child will never grow larger. Not, a parent is also limited by its parent and so on.
精彩评论