2016-11-13 77 views
0

我需要將圖像視圖的頂部與活動的中心對齊。如何將項目的頂部對齊到活動的中心

如果我在android studio中單擊並拖動它,我可以輕鬆地將圖像視圖的中心鏈接到活動的中心。但是我需要頂部的圖像視圖和活動的中心鏈接。

如何以編程方式執行此操作?我無法設置100dp的邊距(例如),因爲它不適用於不同的屏幕尺寸。

+0

您可以在一個RelativeLayout中居中放置一個空視圖,然後將頂部對齊到該空視圖 –

回答

1

我不知道我是否明白你的意思。

我認爲你想要將你的活動佈局分爲兩部分,從屏幕中間開始的Imageview。

我的話,你可以用輕鬆PercentRelativeLayout,這裏的代碼:

的build.gradle

dependencies { 
    compile 'com.android.support:percent:22.2.0' 
} 

layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.percent.PercentRelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

     <ImageView 
      android:src="@color/colorAccent" 
      app:layout_paddingTop="50%" 
      app:layout_heightPercent="50%" 
      app:layout_widthPercent="100%" 
     /> 

     <ImageView 
      android:src="@color/colorPrimary" 
      app:layout_marginTopPercent="50%" 
      app:layout_heightPercent="50%" 
      app:layout_widthPercent="100%" 
     /> 

</android.support.percent.PercentRelativeLayout> 

結果:

visual example

P.S:如果你喜歡,你可以玩佈局重量,並得到相同的結果!