android:如何处理屏幕适配问题?

在安卓开发中,会经常遇到屏幕适配问题,下面总结一下,处理这问题的方法.

解决方法:

手机选择:   

     首先在项目开始时候,应该选择什么屏幕大小的手机,进行开发呢?

用当前市场上主流屏幕的手机,比如 1280*720

   项目后期:还需要用不同分辨率手机进行测试:比如:480*800  1920*1000

图片适配:

  做法:在工程目录:drawable目录中的不同目录,目录不同可以优先对应适配的手机

 

注释:480*800代表分辨率,括号中1.5代表屏幕密度

通常情况下,把图片放在drawalbe-hdpi目录,如果每个目录都放一份图片,那样会造成整个应用会占用太多资源

布局适配

  做法:不要绝对布局,多用相对布局或线性布局权重,用dp,不要px

权重适配:

  做法:是在线性布局中处理   android:weihtSum

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="5"
       >
        
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#0f0" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#00f" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#f0f" />

    
    </LinearLayout>

效果:


尺寸适配:


  dxdp关系:dp = px/设备密度

//设备密度,和手机分辨率有关

Int density = getResouces().getDisplayMetris().density;

问题:当遇到dp解决不了的问题,比如下面代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#00f" />

    <TextView
        android:layout_width="320dp"
        android:layout_height="100dp"
        android:background="#0f0" />

</LinearLayout>


这代码在720*1280 和 320*480中界面显示如下:
 

解决方法:利用values目录下创建dimens.xml,这个目录定义了320*480的尺寸

          创建values-720*1280目录,在这个目录也创建dimens.xml,这个文件定义了720*1280的尺寸

values目录下的dimens.xml

<resources>

    <dimen name="textWith">160dp</dimen>
</resources>


value-720*1280目录下的dimens.xml

<resources>

    <dimen name="textWith">320dp</dimen>
</resources>

代码适配:

Int width = getWindowManager().getDefaultDisplay().getWidth();
Int height = getWindowManager().getDefaultDisplay().getHeight();

TextView tv1 = (TextView)findViewById(R.id.tv1);
TextView tv2 = (TextView)findViewById(R.id.tv2);

LayoutParams params = new LayoutParams(width /3,height*0.2);
tv1.setLayoutParams(params);
tv2.setLayoutParams(params);






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值