이 글에서는 Kotlin을 사용해 Android에서 뷰(View)의 레이아웃 파라미터를 프로그래밍 방식으로 설정하는 방법을 예제와 함께 소개합니다. XML 레이아웃을 수정하지 않고 코드만으로 버튼의 크기를 동적으로 변경하는 전체 과정을 단계별로 따라 할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력해 프로젝트를 만듭니다.
2단계 — activity_main.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:gravity="center"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="expand"
android:text="Hello World"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
3단계 — MainActivity.kt 코드 작성
src/MainActivity.kt 파일에 다음 코드를 추가합니다.
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
}
fun expand(view: View) {
val height = RelativeLayout.LayoutParams.WRAP_CONTENT
val width = 200
val layoutParams = RelativeLayout.LayoutParams(width, height)
val button: Button = findViewById(R.id.button)
button.layoutParams = layoutParams
}
}
위 코드의 핵심은 expand() 메서드입니다. RelativeLayout.LayoutParams(width, height) 객체를 새로 생성해 버튼의 layoutParams에 할당하면, 뷰가 다시 그려지면서 버튼의 너비가 200px로 변경됩니다. 높이는 WRAP_CONTENT 상수를 사용해 콘텐츠 크기에 맞추도록 지정했습니다.
4단계 — AndroidManifest.xml 설정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<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 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘
을 클릭합니다. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.


참고: 실제 레이아웃 가중치(weight)를 코드로 설정하는 방법
LinearLayout 내부에서 뷰의 가중치를 코드로 직접 지정하려면, 세 번째 인자로 weight 값을 받는 LinearLayout.LayoutParams 생성자를 사용하면 됩니다.
val params = LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1f // weight = 1
)
textView.layoutParams = params
너비를 0dp로 설정하고 가중치를 부여하면, 부모 뷰의 남은 공간을 각 뷰가 가중치 비율에 따라 나누어 갖게 됩니다. 이 원리를 응용하면 TextView뿐 아니라 어떤 뷰든 런타임에 유연하게 배치할 수 있습니다.