2016-02-12 31 views
2

我有下面的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:background="#000000" 
       android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_margin="100dp" 
     android:orientation="vertical" 
     android:background="#ff0000"> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:background="#00ff00" 
      android:text="Button" 
      android:layout_gravity="center"/> 
    </LinearLayout> 

</LinearLayout> 

它具有以下設計。

enter image description here

不應在button被放置在中心垂直以及?我知道layout_gravitygravity是如何工作的。所以根據我的理解,按鈕應該在水平方向和垂直方向都處於中心位置。

回答

4

您必須在LinearLayout

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_margin="100dp" 
    android:orientation="vertical" 
    android:gravity="center" 
    android:background="#ff0000"> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="#00ff00" 
     android:text="Button" 
     android:layout_gravity="center"/> 
</LinearLayout> 

+0

這工作正常。謝謝。但是在linearLayout中不添加gravity =「center」,它如何將按鈕放置在水平中心? – thedarkpassenger

+0

你是什麼意思?你不能用其他方式做。由於LinearLayout將方向上的子視圖放置在一個方向上,因此您必須設置重力,以便了解它必須放置的位置 –

0

基於@vspallas答案,我找到了解決我的問題添加android:gravity="center"。基本上這種行爲的原因是我爲我的LinearLayout指定vertical方向。這意味着我在layout內的任何視圖都應該以垂直方向顯示,即一個在另一個之下。如果我有我的LinearLayout內部的三個觀點,那麼結果應該是這樣的

View1 
View2 
View3. 

但是,如果我做了android:layout_gravity="center"用於視圖2和有它的工作,根據我的期望,那麼它會在中心放置View2,而不是在View1View3之間,這與orientation屬性相矛盾。因此,Android允許將引力設置爲父級本身,這將確保所有視圖繼承相同的重力,並且方向相同(LinearLayout)。