java - 改变 textView 的布局引力

标签 java android android-layout android-listview textview

我在 ListView 中有一个 TextView。我正在尝试根据相应的文本更改 textview 的对齐方式。但它不起作用。

谢谢

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);   
} 

我的布局如下:

<?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>

*编辑:* 我知道如何从 xml 文件更改它,但如何从代码更改它?

android:layout_gravity="right"

最佳答案

将textview的宽度设置为match_parent,Gravity设置 View 内部的布局方式,所以如果你将textview的宽度设置为 ListView 项的宽度,然后设置textview的gravity,它会对齐那里的实际文本.

<?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>

我还注意到您在线性布局上设置了引力。我不会尝试将 gravity 和 layout_gravity 混合在一起,只是坚持使用一个。您也可以通过设置线性布局而不是 TextView 的重力来获得所需的效果

关于java - 改变 textView 的布局引力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716499/

相关文章:

java - Java 帮助中的表格格式/printf 间距

java - [Android map API] : Google-play-services prompting update on phone but not in emulator.

android - 为什么我把 if (savedInstanceState != null){} 放在 onCreate 方法中并不重要

Android FloatingActionButton 快速拨号

android - 相对布局中的 layout_below 不会显示

java - 带有 GWT 的 gilead 需要哪些 jar 文件?

java - getGraphics() 阻止我的游戏启动

android - 自定义 ExpandableListview,其中包含子项中的另一个展开按钮

android - 你能解释一下(数学计算)手势示例(Levenshtein)吗?

android - 为什么不能为容器设置 max_width?