Android屏幕适配全攻略

        目前主流屏幕是1280*720,开发后期会在不同分辨率的机型上测试,如480*800的和1920*1080的。如果没出现太大的问题,在不影响使用的情况下,就可以上线了。但或多或少都会出现点小bug,这时候我们开发人员都会在心里默唱草泥马之歌...但是工作还是要做的,所以:

适配原则:

  • 不用绝对布局, 多用相对布局和线性布局。
  • 距离使用dp,而不用px,字体大小用sp。
  • 图片多使用.9的。

1.图片适配


让视觉工程师(也就是美工)多切几套图,放在不同的文件夹下就行了,比较偷懒,项目会增大,不常用。
2.布局适配
写两套布局,专门适配不同的屏幕, layout-800x480 专门适配480*800的屏幕,也不常用。

3.尺寸适配
这里就要说到dp和px的关系了,dp = px/设备密度
<pre name="code" class="html"><span style="font-family:SimSun;font-size:18px;">// 获取设备密度, 和分辨率有关
float density = getResources().getDisplayMetrics().density;
System.out.println("设备密度:" + density);</span>
 
在values中专门指定尺寸大小
<span style="font-size:18px;"><resources>
    <dimen name="textview_width">320dp</dimen>
</resources></span>
有时我们也会在代码中动态设置控件的大小,但是在代码中设置的大小都是以px为单位的,运行起来就会有bug,这时就需要进行px对dp的转换了
<pre name="code" class="html">import android.content.Context;
public class DensityUtils {
	/**
	 * dp转px
	 */
	public static int dp2px(Context context, float dp) {
		// 获取设备密度
		float density = context.getResources().getDisplayMetrics().density;
		int px = (int) (dp * density+0.5f);
		return px;
	}
	/**
	 * xp转dp
	 */
	public static float px2dp(Context context, int px) {
		// 获取设备密度
		float density = context.getResources().getDisplayMetrics().density;
		float dp = px/density;
		return dp;
	}
}
 在动态设置大小时调用一下即可。 
params.leftMargin=DensityUtils.dp2px(this, 10);
4.代码适配
获取屏幕的宽高,动态计算控件的大小。
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);
5.权重适配
<span style="font-size:18px;"> <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3" >

        <Button
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#0f0" />

        <Button
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_weight="1"
            android:background="#00f" />
    </LinearLayout></span>
<span style="font-size:18px;">android:weightSum="3"</span>
比例为3,现只有两个按钮,第三个就会空出来,而这两个按钮无论在什么样的分辨率下,大小都是一样的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yechaoa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值