1. 布局适配

1.1 布局文件夹

为了适配横竖屏,Android提供了专门的布局文件夹:

  • res/layout:默认布局文件夹,适用于竖屏。
  • res/layout-land:横屏布局文件夹,适用于横屏。

将不同屏幕方向的布局文件放置在对应的文件夹中,Android系统会根据当前屏幕方向自动加载相应的布局。

1.2 使用权重

在布局文件中,可以使用权重(weight)来动态调整组件大小。以下是一个使用权重的示例:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:src="@drawable/image" />

</LinearLayout>

在上面的代码中,ImageView组件的宽度和高度都设置为0dp,并通过layout_weight属性设置为1,使其占据剩余空间。

2. 图片处理

2.1 图片资源

  • 在资源文件夹中创建drawable-land文件夹,存放横屏适配的图片资源。
  • 在资源文件夹中创建drawable-port文件夹,存放竖屏适配的图片资源。

2.2 图片加载

int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    imageView.setImageResource(R.drawable.image_land);
} else {
    imageView.setImageResource(R.drawable.image_port);
}

2.3 图片缩放

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, screenWidth, screenHeight, true);
imageView.setImageBitmap(scaledBitmap);

3. 性能优化

3.1 图片缓存

Glide.with(context).load(imageUrl).into(imageView);

3.2 图片压缩

InputStream is = context.getResources().openRawResource(R.drawable.image);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // 压缩比例
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);

4. 总结