首先声明。此种适配方式适用于分辨率差别不是很大的情况下使用。因是通过对布局进行等比例缩放。若要求适配的机型分辨率相差较大。容易出现图片不是很清晰的情况。
首先看布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- 根布局使用全屏显示。作为不变的基准 -->
<!-- 以固定的宽高为基准,宽度为720px,可根据自己需要设定特定的高度或宽度,未设置的部分会在代码中根据计算出的缩放比例计算出来 -->
<FrameLayout
android:id="@+id/scale_root"
android:layout_width="720px"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="60px"
android:text="页首的TextView,占60像素"
android:gravity="center"
android:layout_alignParentTop="true"
android:background="#3000FFFF"
/>
<Button
android:layout_width="match_parent"
android:layout_height="100px"
android:text="页末的Button。占100像素"
android:gravity="center"
android:layout_alignParentBottom="true"
android:background="#30FF00FF"
/>
</RelativeLayout>
</FrameLayout>
</RelativeLayout>
可以看到。这里面我们定义了在根布局下定义了一个scale_root。这个就是专门用来进行缩放的布局。这里我对它的宽度设置成了720px。就是以它为标准来进行缩放。缩放后内部的控件摆放位置也都由这个720px的长度来计算出来。当然这个地方你具体设宽度或者高度为固定值都行。具体看你的项目对宽度或者高度哪方面要求更严格一些。
然后看Activity中的处理:
public class MainActivity extends Activity {
/** 用作缩放标准的根布局 */
private RelativeLayout root;
/**
* 用于缩放适配的布局
*/
private FrameLayout scale_root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (RelativeLayout) findViewById(R.id.root);
scale_root = (FrameLayout) findViewById(R.id.scale_root);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
return;
}
scaleLayout();
}
/** 对整体布局进行缩放 */
private void scaleLayout() {
// 先计算出根布局的宽高。
int scrWidth = root.getMeasuredWidth();
int scrHeight = root.getMeasuredHeight();
// 以一个高度或者宽度的基准来获取缩放因子,这里使用宽度。
float scale = scrWidth / 720f;
/*
* 根据获取的缩放因子,来定义缩放布局的宽高。并根据重新计算出的宽高来重新定义缩放布局的宽高。
*/
LayoutParams lp = scale_root.getLayoutParams();
lp.width = (int) (scrWidth / scale);
lp.height = (int) (scrHeight / scale);
scale_root.setLayoutParams(lp);
// 将root布局移至屏幕中心位置。准备缩放操作
scale_root.setX((scrWidth - lp.width) / 2);
scale_root.setY((scrHeight - lp.height) / 2);
// 进行缩放。
scale_root.setScaleX(scale);
scale_root.setScaleY(scale);
}
}
代码中注释已经很详细了。float scale = scrWidth / 720f;这一句就是以宽度720px的基数来进行缩放。假如你需要的是以高度1080px为基准来缩放。只需要改为float scale = scrHeight / 1080f;即可。