## 屏幕适配 ##
> 主流屏幕: 1280*720, 遵循原则: 不用AbsoluteLayout(绝对布局), 多用相对布局&线性布局(权重), 要用dp,不用px
> 开发后期, 在不同分辨率屏幕上测试(480*800,1920*1080), 如果没出现太大问题(影响正常使用), 就可以上线
> 如果后期测出问题怎么办?
- 图片适配
根据图片的分辨率,放在不同的drawable文件中,然后根据手机的分辨率来适配
- 布局适配
不是很常用, layout-800x480 专门适配480*800的屏幕,单独写一个布局文件来适配
- 尺寸适配
dp和px的关系: dp = px/设备密度
float density = getResources().getDisplayMetrics().density;
System.out.println("设备密度:" + density);
320*240(0.75), 480*320(1),480*800(1.5),1280*720(2)
> 主流屏幕: 1280*720, 遵循原则: 不用AbsoluteLayout(绝对布局), 多用相对布局&线性布局(权重), 要用dp,不用px
> 开发后期, 在不同分辨率屏幕上测试(480*800,1920*1080), 如果没出现太大问题(影响正常使用), 就可以上线
> 如果后期测出问题怎么办?
- 图片适配
根据图片的分辨率,放在不同的drawable文件中,然后根据手机的分辨率来适配
- 布局适配
不是很常用, layout-800x480 专门适配480*800的屏幕,单独写一个布局文件来适配
- 尺寸适配
dp和px的关系: dp = px/设备密度
float density = getResources().getDisplayMetrics().density;
System.out.println("设备密度:" + density);
320*240(0.75), 480*320(1),480*800(1.5),1280*720(2)
values->dimens.xml values-1280x720
写一个工具类,将dp转px来适配屏幕
package com.ldw.screenAdapter.utils;
import android.content.Context;
public class DensityUtils {
/**
* dp转px,屏幕适配
*/
public static int dp2px(Context ctx, float dp) {
float density = ctx.getResources().getDisplayMetrics().density;
int px = (int) (dp * density + 0.5f);// 4.9->5 4.4->4
return px;
}
public static float px2dp(Context ctx, int px) {
float density = ctx.getResources().getDisplayMetrics().density;
float dp = px / density;
return dp;
}
}
- 权重适配
android:weightSum="3" // 总的权重,然后再给子部件设置权重来设定占据空间的大
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3" >
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:background="#0f0" />
<TextView
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_weight="1"
android:background="#00f" />
</LinearLayout>
- 代码适配
获取屏幕宽高,动态计算控件大小
package com.ldw.screenAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
TextView tv1 = (TextView) findViewById(R.id.tv_1);
TextView tv2 = (TextView) findViewById(R.id.tv_2);
LayoutParams params = new LayoutParams(width / 3, (int) (height * 0.2));
tv1.setLayoutParams(params);
tv2.setLayoutParams(params);
}
}