Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sắp xếp View trong RelativeLayout bằng code Java/Kotlin trong Android

Giới thiệu

Bài viết này minh họa cách thêm và định vị các View (Button, TextView...) vào RelativeLayout hoàn toàn bằng code lập trình (programmatically) thay vì XML.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo project Android Studio mới.

Bước 2: Layout XML cơ sở (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/relativelayoutID"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

Bước 3: Code Java thêm View động (src/MainActivity.java)

package com.app.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. Lấy reference đến RelativeLayout cha
        relativeLayout = findViewById(R.id.relativelayoutID);

        // 2. Tạo Button mới hoàn toàn bằng code
        Button dynamicButton = new Button(this);
        dynamicButton.setText("Dynamic Button");

        // 3. Tạo LayoutParams cho RelativeLayout
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        );

        // 4. Thêm quy tắc định vị (Rule) - quan trọng nhất
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        // Các rule khác thường dùng:
        // layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        // layoutParams.addRule(RelativeLayout.BELOW, otherViewId);
        // layoutParams.addRule(RelativeLayout.RIGHT_OF, otherViewId);

        // 5. Áp dụng params cho button
        dynamicButton.setLayoutParams(layoutParams);

        // 6. Thêm event click
        dynamicButton.setOnClickListener(v ->
            Toast.makeText(MainActivity.this, "Clicked on Dynamic button", Toast.LENGTH_LONG).show()
        );

        // 7. Thêm button vào layout cha
        relativeLayout.addView(dynamicButton);
    }
}

Các Rule phổ biến của RelativeLayout.LayoutParams:

RuleMô tả
CENTER_IN_PARENTCăn giữa theo cả ngang và dọc
ALIGN_PARENT_TOP/BOTTOM/LEFT/RIGHTCăn lề trên/dưới/trái/phải parent
BELOW/ABOVE (viewId)Dưới/trên view khác
LEFT_OF/RIGHT_OF (viewId)Trái/phải view khác
ALIGN_TOP/BOTTOM/LEFT/RIGHT (viewId)Căn cùng top/bottom/left/right với view khác

Bước 4: Cấu hình Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.app.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>

Chạy ứng dụng

Chạy app, sẽ thấy một Button "Dynamic Button" xuất hiện chính giữa màn hình, được tạo hoàn toàn bằng code Java.

Cách sắp xếp View trong RelativeLayout bằng code Java/Kotlin trong Android

Kotlin Version

val dynamicButton = Button(this).apply {
    text = "Dynamic Button"
    setOnClickListener { toast("Clicked!") }
}

val params = RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT
).apply {
    addRule(RelativeLayout.CENTER_IN_PARENT)
}

dynamicButton.layoutParams = params
relativeLayout.addView(dynamicButton)