Reputation: 373
I have a TextView
in a ListView
. I am trying to change the alignment of the textview
according to the corresponding text. But it is not working.
Thanks
if (stringItem != null) {
TextView messageText = (TextView) view.findViewById(R.id.list_item_text_view);
if (mine==0)
messageText.setGravity(Gravity.RIGHT);
if (mine==1)
messageText.setGravity(Gravity.LEFT);
messageText.setText(stringItem);
}
and my Layout is as follow:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_item"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="@+id/list_item_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@drawable/self_textview"
android:textSize="20sp" />
</LinearLayout>
*EDIT: * I know how to change it from the xml
file, but how to change it from code ?
android:layout_gravity="right"
Upvotes: 1
Views: 1575
Reputation: 373
I was able to make it work by changing the layoutParams
of a linearlayout
and changing its gravity
then setting it to the textview
.
LinearLayout.LayoutParams para=new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT );
para.gravity = Gravity.RIGHT;
messageText.setLayoutParams(para);
will change the textview's gravity to right.
Upvotes: 0
Reputation: 4408
set the textview width to match_parent, Gravity sets how things are laid out INSIDE of the view, so if you set the textview's width to the list view items width and then set the gravity of the textview it will align the actual text there.
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/list_item_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="@drawable/self_textview"
android:textSize="20sp" />
</LinearLayout>
I also noticed you have the gravity set on the linear layout. I would not try to mix gravity and layout_gravity just stick to one. You might also get the desired effect by setting the gravity of the linear layout instead of the text view
Upvotes: 1