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

Đặt margin cho ImageView bằng code trong Android

Đặt margin cho ImageView bằng code trong Android

Hướng dẫn này minh họa cách thiết lập margin (lề) cho ImageView lập trình thông qua LayoutParams.

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: Thiết kế giao diện (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"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/image"/>
</RelativeLayout>

Bước 3: Chuẩn bị hình ảnh

Copy một file hình ảnh (jpg, png) vào thư mục res/drawable/ và đặt tên là image.jpg (hoặc .png).

Bước 4: Code MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imageView = findViewById(R.id.imageView);
        
        // Lấy LayoutParams phù hợp với ViewGroup cha (RelativeLayout)
        RelativeLayout.LayoutParams layoutParams = 
            (RelativeLayout.LayoutParams) imageView.getLayoutParams();
        
        // Thiết lập margin: left, top, right, bottom (đơn vị: pixel)
        layoutParams.setMargins(100, 100, 100, 100);
        
        // Áp dụng lại LayoutParams
        imageView.setLayoutParams(layoutParams);
    }
}

Bước 5: 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ị, chạy app. ImageView sẽ hiển thị với margin 100px ở 4 cạnh so với viền màn hình.

Quan trọng: LayoutParams phải khớp với ViewGroup CHA
// Nếu cha là RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();

// Nếu cha là LinearLayout
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();

// Nếu cha là FrameLayout
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();

// Nếu cha là ConstraintLayout
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) view.getLayoutParams();

// Nếu cha là CoordinatorLayout
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams();

Chuyển đổi dp sang pixel

public int dpToPx(int dp) {
    return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}

// Sử dụng
int marginDp = 16;
int marginPx = dpToPx(marginDp);
layoutParams.setMargins(marginPx, marginPx, marginPx, marginPx);

Các phương thức LayoutParams hữu ích

// Margin
params.setMargins(left, top, right, bottom);
params.leftMargin = 50;
params.topMargin = 50;

// Gravity (căn chỉnh trong ViewGroup cha)
params.gravity = Gravity.CENTER; // Hoặc Gravity.START, Gravity.END, Gravity.BOTTOM...

// Kích thước
params.width = 200; // pixel
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = ViewGroup.LayoutParams.MATCH_PARENT;

// Weight (chỉ LinearLayout)
params.weight = 1.0f;

// Margin start/end (RTL support)
params.setMarginStart(50);
params.setMarginEnd(50);

Cập nhật layout params an toàn

// Cách an toàn: kiểm tra null
ViewGroup.LayoutParams params = imageView.getLayoutParams();
if (params instanceof RelativeLayout.LayoutParams) {
    RelativeLayout.LayoutParams rlParams = (RelativeLayout.LayoutParams) params;
    rlParams.setMargins(100, 100, 100, 100);
    imageView.setLayoutParams(rlParams);
}

// Hoặc tạo mới (mất các thuộc tính khác như rules)
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT
);
newParams.setMargins(100, 100, 100, 100);
imageView.setLayoutParams(newParams);