android - 在 RelativeLayout 中垂直居中两个 TextView

标签 android android-layout android-relativelayout

发生了什么

我正在编写一个包含两个 TextView 的 PopupWindow,其中第二个 TextView 应在弹出窗口中垂直居中,而第一个 TextView 应直接位于其上方。

问题是 RelativeLayout 似乎将两个 TextView 视为一个元素,并垂直居中它们的中间。不过,我希望下方的 TextView 居中,而上方的 TextView 正好位于其上方(因此 android:layout_above="@id/first_name")。

XML 布局

请注意那里明显不必要的 LinearLayout,因为 RelativeLayout 拒绝完全垂直填充屏幕(PopupWindow 使用 ViewGroup.LayoutParams.MATCH_PARENT)。

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" >

        <TextView
            android:id="@+id/first_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:singleLine="true"
            android:text="Christopher" />

        <TextView
            android:id="@+id/lbl_hello"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@id/first_name"
            android:gravity="center"
            android:singleLine="true"
            android:text="@string/hello" />
    </RelativeLayout>

</LinearLayout>

Java Activity

LayoutInflater inflater = LayoutInflater.from(this);
final View popupView = inflater.inflate(R.layout.<fragment name>,
                                        <parent object>,
                                        false);
final PopupWindow pwindow = new PopupWindow(popupView,
                                            ViewGroup.LayoutParams.MATCH_PARENT,
                                            ViewGroup.LayoutParams.MATCH_PARENT,
                                            true);
pwindow.setTouchable(true);
new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
        pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
    }

}, 100L);

最佳答案

正如 Sushil 所说,您可能可以完全删除 LinearLayout。以下修复应该有效;如果是,请尝试同时删除线性布局。

这里的问题是 RelativeLayout 上的 android:gravity="center"。如果删除它,您可以获得所需的位置:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

关于android - 在 RelativeLayout 中垂直居中两个 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161456/

相关文章:

android - 如果设备语言是阿拉伯语,布局会发生变化

java - 如果我的应用程序正在运行,请更改我在 Android 中的主页!

android - 使用按钮更改属性 use_flash true/false

android - 几秒钟后在 Webview 中加载 url

android - 更改 View 大小以匹配内容

java - Android,添加高度百分比的 View

android - Android从数据库获取数据

android - TextView 未更新?

Android相对布局重力填充问题

java - 设置边距时,相对布局中的按钮会被压扁