在安卓開發中,會經常遇到螢幕适配問題,下面總結一下,處理這問題的方法.
解決方法:
手機選擇:
首先在項目開始時候,應該選擇什麼螢幕大小的手機,進行開發呢?
用目前市場上主流螢幕的手機,比如 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>
效果:
尺寸适配:
dx和dp關系: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);