2017-03-28 16 views
2

達成したいのは、Viewを親レイアウトの中央に配置したいということです。アンドロイドの親ビュー/レイアウトの中心の真上にビューを配置する方法

enter image description here

私は私のViewになりたい青い四角形それ:下の画像を検討します。あなたが見ることができるように、それはちょうど画面の(垂直の)中心の上にあります。

私たちはビューの高さを知りません(私はそれのための下限を使用することはできません)ので、レイアウトxmlファイルでそれをやりたいです(私はコードを使用することはできませんビューの高さを決定し、プログラムでマージンを設定してください)

これを行う方法はありますか?

答えて

4

あなたは私はあなたがConstraintLayoutを使用することをお勧めします

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

    <View android:id="@+id/dummy_view" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_centerInParent="true" 
     /> 
    <View 
     android:id="@+id/your_view" 
     android:layout_width="20dp" 
     android:layout_height="20dp" 
     android:layout_above="@+id/dummy_view" 
     android:layout_centerHorizontal="true" 
     /> 

</RelativeLayout> 
+0

すてきなトリック。ありがとう – roostaamir

1

が、それは簡単なガイドラインを使用して(代わりのアンカーポイントとしてビューを使用して行うことができます希望、場所にであなたのビューを配置するために、次のレイアウトに従うことができます):

Example

XMLの例:

<android.support.constraint.ConstraintLayout 
     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" 
     > 
    <android.support.constraint.Guideline 
      android:id="@+id/mid_guideline" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal" 
      app:layout_constraintGuide_percent="0.5" 
      /> 
    <View 
      android:layout_width="50dp" 
      android:layout_height="50dp" 
      android:background="#F00" 
      app:layout_constraintRight_toRightOf="parent" 
      app:layout_constraintLeft_toLeftOf="parent" 
      app:layout_constraintBottom_toTopOf="@+id/mid_guideline" 
      /> 
</android.support.constraint.ConstraintLayout> 
+1

技術的なガイドライン*は、ビューですが、ええ良い解決策です。 – RobCo

+0

これは、ビューを中央に、もう1つをそのビューの上に置く「RelativeLayout技法」とあまり違いはありません。 –

+1

私は同じですが、RelativeLayoutではなくConstraintLayoutを使用しています。味の物質、私は推測する。 – Arturo

関連する問題