[英]changing textView's layout gravity
I have a TextView
in a ListView
. 我在ListView
有一个TextView
。 I am trying to change the alignment of the textview
according to the corresponding text. 我试图根据相应的文本更改textview
的对齐方式。 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 ? * 编辑:*我知道如何从xml
文件更改它,但是如何从代码更改它?
android:layout_gravity="right"
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. 将textview的宽度设置为match_parent,Gravity设置视图内部布局的方式,因此,如果将textview的宽度设置为列表视图项目的宽度,然后设置textview的重力,它将使实际文本对齐。
<?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. 我不会尝试只将重力和layout_gravity混合使用。 You might also get the desired effect by setting the gravity of the linear layout instead of the text view 您还可以通过设置线性布局的重力而不是文本视图来获得所需的效果
I was able to make it work by changing the layoutParams
of a linearlayout
and changing its gravity
then setting it to the textview
. 我可以通过更改layoutParams
的linearlayout
并更改其gravity
然后将其设置为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. 会将textview的重力更改为右。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.