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

Cách đặt trọng số layout (layout_weight) cho TextView lập trình trong Android

Hướng dẫn này trình bày cách thay đổi kích thước View (Button/TextView) lập trình bằng cách thiết lập LayoutParams trong code Java. Ví dụ minh họa mở rộng Button khi nhấn vào nó.

Lưu ý: Tiêu đề gốc nói về "layout_weight" nhưng code ví dụ thực tế đang set width/height cố định (500px, MATCH_PARENT), không dùng weight. Dưới đây giải thích cả hai cách.

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

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Layout (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">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:onClick="expand"
        android:textSize="24sp"
        android:text="Nhấn để mở rộng"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Bước 3: Code 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;

public class MainActivity extends AppCompatActivity {
    Button button;

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

    // Gọi từ android:onClick="expand" trong XML
    public void expand(View view) {
        int height = RelativeLayout.LayoutParams.MATCH_PARENT;
        int width = 500; // Chiều rộng cố định 500px

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
        button = findViewById(R.id.button);
        button.setLayoutParams(layoutParams);
    }
}

Bước 4: Cấu hình 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút "Nhấn để mở rộng" - Button sẽ giãn rộng chiều ngang 500px và cao full màn hình.

Cách đặt trọng số layout (layout_weight) cho TextView lập trình trong Android Cách đặt trọng số layout (layout_weight) cho TextView lập trình trong Android

Giải thích LayoutParams

Mỗi ViewGroup con (LinearLayout, RelativeLayout, FrameLayout, ConstraintLayout...) có lớp LayoutParams riêng. Khi set lập trình, phải dùng LayoutParams của ViewGroup CHA.

ViewGroup cha LayoutParams tương ứng
LinearLayout LinearLayout.LayoutParams
RelativeLayout RelativeLayout.LayoutParams
FrameLayout FrameLayout.LayoutParams
ConstraintLayout ConstraintLayout.LayoutParams
GridLayout GridLayout.LayoutParams

Cách dùng layout_weight lập trình (LinearLayout)

Nếu View cha là LinearLayout và muốn set weight:

// Giả sử cha là LinearLayout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        0, // width = 0 khi dùng weight
        LinearLayout.LayoutParams.WRAP_CONTENT
);
params.weight = 1.0f; // Trọng số
textView.setLayoutParams(params);
  • width = 0 (hoặc height = 0 cho vertical) khi dùng weight
  • weight là float (1.0f, 2.0f, 0.5f...)

Cách dùng ConstraintLayout lập trình

ConstraintLayout phức tạp hơn, cần ConstraintSet:

ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);

// Thay đổi kích thước
constraintSet.constrainWidth(R.id.textView, 300);
constraintSet.constrainHeight(R.id.textView, ConstraintSet.WRAP_CONTENT);

// Áp dụng
constraintSet.applyTo(constraintLayout);

Tóm tắt

  • Luôn dùng LayoutParams của ViewGroup cha
  • Dùng MATCH_PARENT, WRAP_CONTENT hoặc pixel cụ thể
  • Với weight: chỉ LinearLayout hỗ trợ, set width/height = 0
  • Cập nhật constraint: dùng ConstraintSet