본문

안드로이드에서 레이아웃, 컨트롤 움직이기



RelativeLayout 관리자는 하위 컨트롤을 배치할 때 컨테이너 뷰나 다른 컨트롤에 대한 상대적 위치를 지정하여 배치한다. alignParent~는 부모의 레이아웃상에서의 경계까지 도달할지 안할지를 결정한다. 아래에서는 alignParentBottom, Left, Right, Top 모두에 true가 설정되어있으므로, 부모 레이아웃에 꽉 채워서 해당 레이아웃을 위치한다는것을 명시한다. 그리고 gravity는 자식 레이아웃의 배치를 결정하며, center의 경우, 자식 항목들이 가운데에 위치하도록 한다.


activity_main.xml

<RelativeLayout

    android:id="@+id/rl" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center"

    android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"

    android:layout_alignParentRight="true" android:layout_alignParentTop="true" >

 

     <TextView android:id="@+id/number" android:text="@string/hello_world"

         android:layout_width="wrap_content" android:layout_height="wrap_content" />

   

</RelativeLayout>



MainActivity.java

① 상위 레이아웃에서의 padding값을 수정해서 자식 항목을 이동시킨다

RelativeLayout rl=(RelativeLayout)findViewById(R.id.rl);

rl.setPadding(move.x, move.y, 0, 0);


② 해당 항목의 layoutparam에서의 margin을 변경하여 자신을 이동한다.

TextView textView=(TextView)findViewById(R.id.number);

MarginLayoutParams params=(MarginLayoutParams) textView.getLayoutParams();

params.leftMargin=move.x;

params.topMargin=move.y;

textView.setLayoutParams(params);


RelativeLayout 배치에 대한 상세사항은 "RelativeLayout - 상대배치" 페이지를 참고할 수 있다. 또한 LayoutParam에 대해서는 "4. 화면 배치를 결정하는 LayoutParams에 대해서" 페이지를 참고할 수 있다. 그리고 물론 AbsoluteLayout을 사용한다면 절대좌표를 사용하여 화면 배치를 수행할 수 있다. 하지만 개인적으로는 직접 '때려박는' 구현을 좋아하지 않아서 거의 사용하지 않는다


또한, margin과 padding에 대한 사항은 android developer 사이트의 Layouts - Size, Padding and Margins 에 아래와 같이 기재되어 있다. 즉, padding을 사용하여 해당 레이아웃을 이동하는것이 합당한 것이다. 여기에 padding은 뷰의 안쪽부분이고 margin은 뷰의 바깥쪽을 나타낸다는 사실을 덧붙이면 더 이해하기 쉬울 것이다. 그리고 css에서와 마찬가지로, 여기에는 negative 값이 허용된다.


To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom().


Even though a view can define a padding, it does not provide any support for margins. However, view groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutParams for further information.

댓글

Holic Spirit :: Tistory Edition

design by tokiidesu. powerd by kakao.