개요
이 튜토리얼에서는 안드로이드 앱에서 뷰(View)의 위치를 코드로 동적으로 변경하는 방법을 알아봅니다. 예제에서는 화면 중앙에 배치된 버튼을 클릭하면 TextView가 해당 버튼 바로 아래로 이동하도록 구현합니다. 핵심 요소는 RelativeLayout.LayoutParams와 addRule() 메서드입니다.
1단계 — 새 프로젝트 생성
Android Studio를 열고 File ⇒ New Project로 이동한 뒤, 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 XML 작성
다음 코드를 res/layout/activity_main.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp" android:textStyle="bold|italic" android:text="Sample TextView" android:padding="10dp" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Put text below this button" android:layout_centerInParent="true" /> </RelativeLayout>
레이아웃에는 TextView 하나와, layout_centerInParent 속성으로 화면 중앙에 배치된 Button 하나가 포함되어 있습니다.
3단계 — MainActivity 작성
다음 코드를 src/MainActivity.java에 추가합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
Button button;
TextView textView;
RelativeLayout relativeLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = findViewById(R.id.relativeLayout);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
layoutParams.addRule(RelativeLayout.BELOW, button.getId());
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, button.getId());
textView.setLayoutParams(layoutParams);
}
});
}
}동작 원리
버튼이 클릭되면 다음과 같은 순서로 처리됩니다.
textView.getLayoutParams()로 현재 뷰의 레이아웃 파라미터를 가져와RelativeLayout.LayoutParams타입으로 캐스팅합니다.addRule(RelativeLayout.BELOW, button.getId())을 호출해 TextView를 버튼 아래에 배치하는 규칙을 추가합니다.addRule(RelativeLayout.ALIGN_LEFT, button.getId())을 호출해 TextView의 왼쪽 가장자리를 버튼의 왼쪽 가장자리에 맞춥니다.setLayoutParams(layoutParams)를 호출해 변경된 위치를 즉시 화면에 반영합니다.
4단계 — 매니페스트 파일
다음 코드를 androidManifest.xml에 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
앱 실행하기
이제 애플리케이션을 실행해 보겠습니다. 여기서는 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 표시됩니다.


버튼을 클릭하면 TextView가 버튼 아래 왼쪽 정렬 위치로 즉시 이동하는 것을 확인할 수 있습니다. 이처럼 LayoutParams와 addRule()을 조합하면 XML 수정 없이도 런타임 중 뷰의 상대적 위치를 자유롭게 제어할 수 있습니다.