TextView Gravity не работает должным образом в android

что не так с моим кодом, я пытаюсь отобразить свой TextView с именем "invalid", в разных местах (слева,справа,в центре), но гравитация (слева,справа,в центре) не будет работать! enter image description here

мой текст.xml-это

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etext"
        android:hint="@string/comment"
        android:inputType="textPassword"/>

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="100">
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/button" 
            android:layout_weight="25"/>

        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:text="ToggleButton" 
            android:layout_weight="75"
            android:checked="true"
            android:paddingLeft="15dp"/>
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/invalid"
        android:layout_gravity="center"
        android:gravity="center" />
</LinearLayout>

Мой TextPlay.java это

public class TextPlay extends Activity {
    Button button;
    ToggleButton tbutton;
    TextView tview;
    EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);
        button = (Button) findViewById(R.id.button1);
        tbutton = (ToggleButton) findViewById(R.id.toggleButton1);
        tview = (TextView) findViewById(R.id.textView1);
        et = (EditText) findViewById(R.id.etext);
        tbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (tbutton.isChecked()) {
                    et.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                } else {
                    et.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String input = et.getText().toString();
                System.out.println(input);
                if (input.contentEquals("left")) {
                    tview.setGravity(Gravity.LEFT);
                } else if (input.contentEquals("right")) {
                    System.out.println("inside right");
                    tview.setGravity(Gravity.RIGHT);
                } else if (input.contentEquals("right")) {
                    tview.setGravity(Gravity.CENTER);
                }
            }
        });
    }
}

5 ответов


вы устанавливаете этот текстовый вид шириной"wrap_content в качестве параметров " это означает, что какой бы текст ни был, вид принимает размер текста.

и LinearLayout , гравитация по умолчанию (здесь)'центр'

вы должны попробовать это :

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"   <= change this
android:layout_height="wrap_content"
android:text="@string/invalid"
android:gravity="center"   <= then this gravity will be taken into account
/>

99% времени not working properly ==not used properly.

Вы путаете gravity и layout_gravity.

gravity - это способ выравнивания текста на TextView. The TextView находясь в wrap_content это ничего не делает, как TextView - это точно размер текста.

layout_gravity так TextView будет выравниваться в своем родителе, в вашем случае по вертикали LinearLayout


вы дали свой TextView width wrap_content, и в этом проблема, Проверьте ниже код и замените его на свой код.

<TextView
android:id="@+id/txtInvalid"
android:layout_width="match_parent"   
android:layout_height="wrap_content"
android:text="@string/invalid"
android:gravity="center"   
/>

set android:layout_width="fill_parent" для textView1


убедитесь, что у вас нет чего-то подобного, висящего вокруг

app:layout_box="left|top"