Search code examples
androidbuttonalignmentcenter

How do I align the right/left side of a button in android to the center of the screen?


I was thinking it would be something like android:layout_startOf"centerHoriztonal" or something like that but I have searched and couldn't find anything. If it helps I am trying to make a soundboard app where all the buttons can be the same size across multiple device screens.


Solution

  • You can wrap the button(s) inside a horizontal LinearLayout and use layout_weight to divide the screen in half and then layout_alignParentLeft/layout_alignParentRight to align the buttons inside a RelativeLayout that takes up exactly half the screen width.

     <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
    
         <RelativeLayout
            android:layout_width="0px"
            android:layout_height="wrap_content"
            android:layout_weight="1">
    
             <Button 
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_alignParentRight="true"
                 android:text="Button Text"
                 /> 
         </RelativeLayout>
    
         <RelativeLayout
            android:layout_width="0px"
            android:layout_height="wrap_content"
            android:layout_weight="1">
    
         </RelativeLayout>
    
     </LinearLayout>
    

    Another way to do it is to create a dummy view object that is centered horizontally in the parent view, and align your buttons to the left or right of it:

       <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
          <View
            android:id="@+id/dummyview"
            android:layout_width="0px"
            android:layout_height="0px"
            android:layout_centerHorizontal="true"/>
    
          <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/dummyview"
            android:text="Button Text"/>
    
      </RelativeLayout>