2011-10-25 30 views
25

我有意見RelativeLayout使用(例如)相一致,以它(其父):Android - 如何將視圖放置在相對於其父項的中心/頂部/底部(等)的偏移量中?

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
       RelativeLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); 
textView.setLayoutParams(layoutParams); 

,現在我不知道,我怎麼能查看相對於其父的底部位置,但在一個偏移量(例如,底部以上100像素,左邊20像素等),或者類似於中心(中心下面30個像素)?

schematic image of the necessary layout

我已經嘗試設置視圖(例如)的邊緣:

layoutParams.setMargins(140, 0, 0, 0); 

它應用到textView,但沒有工作之前。

這似乎是一個非常有用的方式來調整視圖的各種屏幕尺寸。

對我來說,在代碼中實現這一點很重要,不使用xmls。

謝謝!

+0

從xml創建佈局這是創建.. –

+0

@PolamReddy對不起,我不明白。你能改說嗎? – DannyA

+0

您動態創建它是一些困難的事情,從xml文件創建將易於創建的佈局。 –

回答

53

你有2種方式,在easies使用位於中央的錨空視圖

<View 
     android:id="@+id/anchor" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_centerInParent="true" /> 


<TextView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@id/anchor" 
    android:layout_marginBottom="20dp" 
    android:text="hello world!"/> 

或者你可以居中您的查看和使用pading POR定位(因​​爲它下面溢出你必須加倍使用的填充屏幕的中心)

<TextView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerInParent="true" 
     android:paddingBottom="40dp" 
     android:text="hello world!"/> 
+0

什麼是復活:)。你會說利弊:錨方法有點容易使用,但可能會浪費更多的CPU /內存資源(使相對佈局樹更大)?另外,我最初的問題需要在代碼中完成。有沒有更多的比使用類似:layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT,0)?謝謝! – DannyA

+0

對於一個簡單的視圖,你有幾個元素,這完美的作品! – Vladimir

0

我剛開始的Android編程今晚,所以這可能是舊的或一個壞主意...但我與上述答案修修補補,發現下面的定位我的其他元素的元素是造成一個問題 - 無論是填充無線ld在路上或某事。這是我最終做的。

使用錨定技術,我也給錨點一個高度(你需要的兩倍),然後將我的元素與頂部對齊。這樣它會在視圖的中間減去錨的一半高度!

<View 
    android:id="@+id/anchor" 
    android:layout_width="0dp" 
    android:layout_height="200dp" 
    android:layout_centerInParent="true" /> 

<TextView 
    android:id="@+id/heading" 
    android:text="@string/heading" 
    android:textColor="@android:color/white" 
    android:textSize="24sp" 
    android:layout_alignTop="@id/anchor" 
    android:layout_centerHorizontal="true" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

<TextView 
    android:id="@+id/subheading" 
    android:text="@string/subheading" 
    android:textColor="@android:color/white" 
    android:textSize="12sp" 
    android:layout_below="@+id/heading" 
    android:layout_centerHorizontal="true" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

其他答案幫了很多,但我只是想給我2美分!

相關問題