安卓layout_gravity

标签 android

我不明白为什么以下代码将我的 TextView 放在屏幕的左上角。根据我对 layout_gravity 的理解,它似乎应该将我的 TextView 放在屏幕底部。

任何人都可以为我解释一下吗?这种线性布局,尽管看起来非常简单,却让我头疼不已。看起来如此简单的事情怎么会如此难以掌握?

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="#FF0000">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello"
            android:layout_gravity="bottom"
            android:background="#FFF"
            />    

    </LinearLayout>

最佳答案

设置为垂直方向的 LinearLayout 将忽略所有涉及垂直对齐的 layout_gravity 参数。因此,例如“底部”将不起作用,但“水平中心”将起作用。 (始终进行垂直对齐,以便布局中的每个 View 都位于布局中其他 View 的下方。)

相对布局可能是可行的方法,或者您可以使用可能非常接近您想要的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#FF0000"
>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:gravity="bottom"
        android:layout_weight="1.0"
        android:background="#FFF" />

</LinearLayout>

编辑blog进一步解释。

关于安卓layout_gravity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10260766/

相关文章:

android - 如何设置Bottomsheet的最大高度可以以其他方式设置WRAP_CONTENT?

android - 在 headless (headless)模式下获取本地化字符串

java - 自动启动和停止方法

android - 如何以编程方式更改 WindowManager.LayoutParams 的类型?

android - 手动向 Android Vitals 报告崩溃

android - 从文件加载纹理问题Android NDK和OpenGL

android - Android 上的 jQuery Mobile + Phonegap - 无 Ajax

android - 无法使用 Samsung Galaxy S2 进行录音,但可以通过麦克风使用其他手机进行录音

java - Android Wear 与手机通信

android - Request 帮助在 Android 中编写 HTTP 请求