簡體   English   中英

RelativeLayout重心不起作用

[英]RelativeLayout gravity center not working

我試圖在作為基礎的RelativeLayout中水平居中幾個視圖。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:background="@android:color/transparent" >

這不起作用。 我已經將其中一個視圖的centerInParent設置為true ,並且確實有效。 但是,我無法使用此解決方案,因為我有兩個並排的視圖需要集中在一起。 試圖優化這個,所以我想避免嵌套布局,特別是線性,彼此內部。

有什么明顯的東西讓我失蹤嗎? 我認為這個屬性是針對這種情況做出的。

我在沒有使用嵌套ViewGroup的情況下回答了涉及三個視圖的類似問題。

https://stackoverflow.com/a/13279846/1011746

這在API 11中進行了測試。

對於兩個視圖水平情況:

<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_toRightOf="@id/apply"
    />
</RelativeLayout>

對於兩個視圖垂直情況:

<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_below="@id/apply"
    />
</RelativeLayout>

您需要將多個布局嵌套在一起。 要將某些內容置於RelativeLayout中,您可以在子項上使用android:layout_centerInParent="true" 如果你試圖讓幾個孩子居中,他們最終會在對方之下。

因此,例如,您可以使用具有兩個視圖的LinearLayout作為RelativeLayout的子視圖,其中LinearLayout具有android:orientation="horizontal"android:layout_centerInParent="true" LinearLayout現在應該在RelativeLayout中居中,兩個孩子彼此相鄰。

將兩個視圖包裝在LinearLayout中,然后將LinearLayout置於RelativeLayout中,就像您對單個TextView所做的那樣。

所以我對這個問題的解決方法只是為了利用textview的復合drawable功能。 我只是刪除了按鈕並使用drawableRight來顯示搜索圖標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM