发生了什么
我正在编写一个包含两个 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/