Giới thiệu
Hướng dẫn này trình bày cách tạo ImageView và đặt kích thước (width/height) cho nó theo chương trình trong Android, sau đó thêm vào RelativeLayout container.
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: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/rlMain"
android:layout_height="match_parent"
android:layout_margin="16dp" />
Bước 3: Viết logic xử lý (src/MainActivity.java)
package app.com.sample;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Lấy container RelativeLayout
RelativeLayout rlMain = findViewById(R.id.rlMain);
// Tạo ImageView mới
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher_background);
// Tạo LayoutParams cho RelativeLayout
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
// Có thể thêm quy tắc định vị (rules) cho RelativeLayout
// params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
imageView.setLayoutParams(params);
// Thêm vào container
rlMain.addView(imageView);
}
}
Bước 4: Cấu hình Manifest (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>
Các loại LayoutParams phổ biến
| Container | LayoutParams Class |
|---|---|
| LinearLayout | LinearLayout.LayoutParams |
| RelativeLayout | RelativeLayout.LayoutParams |
| ConstraintLayout | ConstraintLayout.LayoutParams |
| FrameLayout | FrameLayout.LayoutParams |
| ViewGroup (cơ bản) | ViewGroup.LayoutParams |
Đặt kích thước cụ thể (dp/px)
// Chuyển đổi dp sang pixel
int sizeInDp = 200;
float scale = getResources().getDisplayMetrics().density;
int sizeInPx = (int) (sizeInDp * scale + 0.5f);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
sizeInPx, sizeInPx
);
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. ImageView sẽ lấp đầy toàn bộ RelativeLayout (trừ margin 16dp).
