## 支持各種屏幕尺寸
### 使用wrap_content、match_parent、weight
要確保布局的靈活性并適應各種尺寸的屏幕,應使用 “wrap_content” 和 “match_parent” 控制某些視圖組件的寬度和高度。
使用 “wrap_content”,系統就會將視圖的寬度或高度設置成所需的最小尺寸以適應視圖中的內容,而 “match_parent”(在低于 API 級別 8 的級別中稱為 “fill_parent”)則會展開組件以匹配其父視圖的尺寸。
如果使用 “wrap_content” 和 “match_parent” 尺寸值而不是硬編碼的尺寸,視圖就會相應地僅使用自身所需的空間或展開以填滿可用空間。此方法可讓布局正確適應各種屏幕尺寸和屏幕方向。
下面是一段示例代碼
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:id="@+id/linearLayout1"
android:gravity="center"
android:layout_height="50dp">
<ImageView android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/logo"
android:paddingRight="30dp"
android:layout_gravity="left"
android:layout_weight="0" />
<View android:layout_height="wrap_content"
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_weight="1" />
<Button android:id="@+id/categorybutton"
android:background="@drawable/button_bg"
android:layout_height="match_parent"
android:layout_weight="0"
android:layout_width="120dp"
style="@style/CategoryButtonStyle"/>
</LinearLayout>
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
~~~
下圖是在橫縱屏切換的時候的顯示效果,我們可以看到這樣可以很好的適配屏幕尺寸的變化。

weight是線性布局的一個獨特的屬性,我們可以使用這個屬性來按照比例對界面進行分配,完成一些特殊的需求。
但是,我們對于這個屬性的計算應該如何理解呢?
首先看下面的例子,我們在布局中這樣設置我們的界面

我們在布局里面設置為線性布局,橫向排列,然后放置兩個寬度為0dp的按鈕,分別設置weight為1和2,在效果圖中,我們可以看到兩個按鈕按照1:2的寬度比例正常排列了,這也是我們經常使用到的場景,這是時候很好理解,Button1的寬度就是1/(1+2) = 1/3,Button2的寬度則是2/(1+2) = 2/3,我們可以很清楚的明白這種情景下的占比如何計算。
但是假如我們的寬度不是0dp(wrap_content和0dp的效果相同),則是match_parent呢?
下面是設置為match_parent的效果

我們可以看到,在這種情況下,占比和上面正好相反,這是怎么回事呢?說到這里,我們就不得不提一下weight的計算方法了。
android:layout_weight的真實含義是:如果View設置了該屬性并且有效,那么該 View的寬度等于原有寬度(android:layout_width)加上剩余空間的占比。
從這個角度我們來解釋一下上面的現象。在上面的代碼中,我們設置每個Button的寬度都是match_parent,假設屏幕寬度為L,那么每個Button的寬度也應該都為L,剩余寬度就等于L-(L+L)= -L。
Button1的weight=1,剩余寬度占比為1/(1+2)= 1/3,所以最終寬度為L+1/3*(-L)=2/3L,Button2的計算類似,最終寬度為L+2/3(-L)=1/3L。
這是在水平方向上的,那么在垂直方向上也是這樣嗎?
下面是測試代碼和效果
如果是垂直方向,那么我們應該改變的是layout_height的屬性,下面是0dp的顯示效果

下面是match_parent的顯示效果,結論和水平是完全一樣的

雖然說我們演示了match_parent的顯示效果,并說明了原因,但是在真正用的時候,我們都是設置某一個屬性為0dp,然后按照權重計算所占百分比。
### 使用相對布局,禁用絕對布局
在開發中,我們大部分時候使用的都是線性布局、相對布局和幀布局,絕對布局由于適配性極差,所以極少使用。
由于各種布局的特點不一樣,所以不能說哪個布局好用,到底應該使用什么布局只能根據實際需求來確定。我們可以使用 LinearLayout 的嵌套實例并結合 “wrap_content” 和 “match_parent”,以便構建相當復雜的布局。不過,我們無法通過 LinearLayout 精確控制子視圖的特殊關系;系統會將 LinearLayout 中的視圖直接并排列出。
如果我們需要將子視圖排列出各種效果而不是一條直線,通常更合適的解決方法是使用 RelativeLayout,這樣就可以根據各組件之間的特殊關系指定布局了。例如,我們可以將某個子視圖對齊到屏幕左側,同時將另一個視圖對齊到屏幕右側。
下面的代碼以官方Demo為例說明。
~~~
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="@+id/entry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="OK" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
~~~
在上面的代碼中我們使用了相對布局,并且使用alignXXX等屬性指定了子控件的位置,下面是這種布局方式在應對屏幕變化時的表現
在小尺寸屏幕的顯示

在平板的大尺寸上的顯示效果

雖然控件的大小由于屏幕尺寸的增加而發生了改變,但是我們可以看到,由于使用了相對布局,所以控件之前的位置關系并沒有發生什么變化,這說明我們的適配成功了。
### 使用限定符
#### 使用尺寸限定符
上面所提到的靈活布局或者是相對布局,可以為我們帶來的優勢就只有這么多了。雖然這些布局可以拉伸組件內外的空間以適應各種屏幕,但它們不一定能為每種屏幕都提供最佳的用戶體驗。因此,我們的應用不僅僅只實施靈活布局,還應該應針對各種屏幕配置提供一些備用布局。
如何做到這一點呢?我們可以通過使用配置限定符,在運行時根據當前的設備配置自動選擇合適的資源了,例如根據各種屏幕尺寸選擇不同的布局。
很多應用會在較大的屏幕上實施“雙面板”模式,即在一個面板上顯示項目列表,而在另一面板上顯示對應內容。平板電腦和電視的屏幕已經大到可以同時容納這兩個面板了,但手機屏幕就需要分別顯示。因此,我們可以使用以下文件以便實施這些布局:
res/layout/main.xml,單面板(默認)布局:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
~~~
res/layout-large/main.xml,雙面板布局:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
~~~
請注意第二種布局名稱目錄中的 large 限定符。系統會在屬于較大屏幕(例如 7 英寸或更大的平板電腦)的設備上選擇此布局。系統會在較小的屏幕上選擇其他布局(無限定符)。
#### 使用最小寬度限定符
在版本低于 3.2 的 Android 設備上,開發人員遇到的問題之一是“較大”屏幕的尺寸范圍,該問題會影響戴爾 Streak、早期的 Galaxy Tab 以及大部分 7 英寸平板電腦。即使這些設備的屏幕屬于“較大”的尺寸,但很多應用可能會針對此類別中的各種設備(例如 5 英寸和 7 英寸的設備)顯示不同的布局。這就是 Android 3.2 版在引入其他限定符的同時引入“最小寬度”限定符的原因。
最小寬度限定符可讓您通過指定某個最小寬度(以 dp 為單位)來定位屏幕。例如,標準 7 英寸平板電腦的最小寬度為 600 dp,因此如果您要在此類屏幕上的用戶界面中使用雙面板(但在較小的屏幕上只顯示列表),您可以使用上文中所述的單面板和雙面板這兩種布局,但您應使用 sw600dp 指明雙面板布局僅適用于最小寬度為 600 dp 的屏幕,而不是使用 large 尺寸限定符。
res/layout/main.xml,單面板(默認)布局:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
~~~
res/layout-sw600dp/main.xml,雙面板布局:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
~~~
也就是說,對于最小寬度大于等于 600 dp 的設備,系統會選擇 layout-sw600dp/main.xml(雙面板)布局,否則系統就會選擇 layout/main.xml(單面板)布局。
但 Android 版本低于 3.2 的設備不支持此技術,原因是這些設備無法將 sw600dp 識別為尺寸限定符,因此我們仍需使用 large 限定符。這樣一來,就會有一個名稱為 res/layout-large/main.xml 的文件(與 res/layout-sw600dp/main.xml 一樣)。但是沒有太大關系,我們將馬上學習如何避免此類布局文件出現的重復。
#### 使用布局別名
最小寬度限定符僅適用于 Android 3.2 及更高版本。因此,如果我們仍需使用與較低版本兼容的概括尺寸范圍(小、正常、大和特大)。例如,如果要將用戶界面設計成在手機上顯示單面板,但在 7 英寸平板電腦、電視和其他較大的設備上顯示多面板,那么我們就需要提供以下文件:
* res/layout/main.xml: 單面板布局
* res/layout-large: 多面板布局
* res/layout-sw600dp: 多面板布局
后兩個文件是相同的,因為其中一個用于和 Android 3.2 設備匹配,而另一個則是為使用較低版本 Android 的平板電腦和電視準備的。
要避免平板電腦和電視的文件出現重復(以及由此帶來的維護問題),您可以使用別名文件。例如,您可以定義以下布局:
* res/layout/main.xml,單面板布局
* res/layout/main_twopanes.xml,雙面板布局
然后添加這兩個文件:
res/values-large/layout.xml:
~~~
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
~~~
res/values-sw600dp/layout.xml:
~~~
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
~~~
后兩個文件的內容相同,但它們并未實際定義布局。它們只是將 main 設置成了 main_twopanes 的別名。由于這些文件包含 large 和 sw600dp 選擇器,因此無論 Android 版本如何,系統都會將這些文件應用到平板電腦和電視上(版本低于 3.2 的平板電腦和電視會匹配 large,版本高于 3.2 的平板電腦和電視則會匹配 sw600dp)。
#### 使用屏幕方向限定符
某些布局會同時支持橫向模式和縱向模式,但我們可以通過調整優化其中大部分布局的效果。在新聞閱讀器示例應用中,每種屏幕尺寸和屏幕方向下的布局行為方式如下所示:
* 小屏幕,縱向:單面板,帶徽標
* 小屏幕,橫向:單面板,帶徽標
* 7 英寸平板電腦,縱向:單面板,帶操作欄
* 7 英寸平板電腦,橫向:雙面板,寬,帶操作欄
* 10 英寸平板電腦,縱向:雙面板,窄,帶操作欄
* 10 英寸平板電腦,橫向:雙面板,寬,帶操作欄
* 電視,橫向:雙面板,寬,帶操作欄
因此,這些布局中的每一種都定義在了 res/layout/ 目錄下的某個 XML 文件中。為了繼續將每個布局分配給各種屏幕配置,該應用會使用布局別名將兩者相匹配:
res/layout/onepane.xml:(單面板)
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
~~~
res/layout/onepane_with_bar.xml:(單面板帶操作欄)
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:id="@+id/linearLayout1"
android:gravity="center"
android:layout_height="50dp">
<ImageView android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/logo"
android:paddingRight="30dp"
android:layout_gravity="left"
android:layout_weight="0" />
<View android:layout_height="wrap_content"
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_weight="1" />
<Button android:id="@+id/categorybutton"
android:background="@drawable/button_bg"
android:layout_height="match_parent"
android:layout_weight="0"
android:layout_width="120dp"
style="@style/CategoryButtonStyle"/>
</LinearLayout>
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
~~~
res/layout/twopanes.xml:(雙面板,寬布局)
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
~~~
res/layout/twopanes_narrow.xml:(雙面板,窄布局)
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="200dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
~~~
既然我們已定義了所有可能的布局,那就只需使用配置限定符將正確的布局映射到各種配置即可。
現在只需使用布局別名技術即可做到這一點:
res/values/layouts.xml:
~~~
<resources>
<item name="main_layout" type="layout">@layout/onepane_with_bar</item>
<bool name="has_two_panes">false</bool>
</resources>
~~~
res/values-sw600dp-land/layouts.xml:
~~~
<resources>
<item name="main_layout" type="layout">@layout/twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>
~~~
res/values-sw600dp-port/layouts.xml:
~~~
<resources>
<item name="main_layout" type="layout">@layout/onepane</item>
<bool name="has_two_panes">false</bool>
</resources>
~~~
res/values-large-land/layouts.xml:
~~~
<resources>
<item name="main_layout" type="layout">@layout/twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>
~~~
res/values-large-port/layouts.xml:
~~~
<resources>
<item name="main_layout" type="layout">@layout/twopanes_narrow</item>
<bool name="has_two_panes">true</bool>
</resources>
~~~
#### 使用自動拉伸位圖
支持各種屏幕尺寸通常意味著您的圖片資源還必須能適應各種尺寸。例如,無論要應用到什么形狀的按鈕上,按鈕背景都必須能適應。
如果在可以更改尺寸的組件上使用了簡單的圖片,您很快就會發現顯示效果多少有些不太理想,因為系統會在運行時平均地拉伸或收縮您的圖片。解決方法為使用自動拉伸位圖,這是一種格式特殊的 PNG 文件,其中會指明可以拉伸以及不可以拉伸的區域。
.9的制作,實際上就是在原圖片上添加1px的邊界,然后按照我們的需求,把對應的位置設置成黑色線,系統就會根據我們的實際需求進行拉伸。
下圖是對.9圖的四邊的含義的解釋,左上邊代表拉伸區域,右下邊代表padding box,就是間隔區域,在下面,我們給出一個例子,方便大家理解。

先看下面兩張圖,我們理解一下這四條線的含義。

上圖和下圖的區別,就在于右下邊的黑線不一樣,具體的效果的區別,看右邊的效果圖。上圖效果圖中深藍色的區域,代表內容區域,我們可以看到是在正中央的,這是因為我們在右下邊的是兩個點,這兩個點距離上下左右四個方向的距離就是padding的距離,所以深藍色內容區域在圖片正中央,我們再看下圖,由于右下邊的黑線是圖片長度,所以就沒有padding,從效果圖上的表現就是深藍色區域和圖片一樣大,因此,我們可以利用右下邊來控制內容與背景圖邊緣的padding。

如果你還不明白,那么我們看下面的效果圖,我們分別以圖一和圖二作為背景圖,下面是效果圖。
我們可以看到,使用wrap_content屬性設置長寬,圖一比圖二的效果大一圈,這是為什么呢?還記得我上面說的padding嗎?

這就是padding的效果提現,怎么證明呢?我們再看下面一張圖,給圖一添加padding=0,這樣背景圖設置的padding效果就沒了,是不是兩個一樣大了?

ok,我想你應該明白右下邊的黑線的含義了,下面我們再看一下左上邊的效果。
下面我們只設置了左上邊線,效果圖如下

上面的線沒有包住圖標,下面的線正好包住了圖標,從右邊的效果圖應該可以看出差別,黑線所在的區域就是拉伸區域,上圖黑線所在的全是純色,所以圖標不變形,下面的拉伸區域包裹了圖標,所以在拉伸的時候就會對圖標進行拉伸,但是這樣就會導致圖標變形。注意到下面紅線區域了嘛?這是系統提示我們的,因為這樣拉伸,不符合要求,所以會提示一下。

## 支持各種屏幕密度
### 使用非密度制約像素
由于各種屏幕的像素密度都有所不同,因此相同數量的像素在不同設備上的實際大小也有所差異,這樣使用像素定義布局尺寸就會產生問題。因此,請務必使用 dp 或 sp 單位指定尺寸。dp 是一種非密度制約像素,其尺寸與 160 dpi 像素的實際尺寸相同。sp 也是一種基本單位,但它可根據用戶的偏好文字大小進行調整(即尺度獨立性像素),因此我們應將該測量單位用于定義文字大小。
例如,請使用 dp(而非 px)指定兩個視圖間的間距:
~~~
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clickme"
android:layout_marginTop="20dp" />
~~~
請務必使用 sp 指定文字大小:
~~~
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
~~~
除了介紹這些最基礎的知識之外,我們下面再來討論一下另外一個問題。
經過上面的介紹,我們都清楚,為了能夠規避不同像素密度的陷阱,Google推薦使用dp來代替px作為控件長度的度量單位,但是我們來看下面的一個場景。
假如我們以Nexus5作為書寫代碼時查看效果的測試機型,Nexus5的總寬度為360dp,我們現在需要在水平方向上放置兩個按鈕,一個是150dp左對齊,另外一個是200dp右對齊,中間留有10dp間隔,那么在Nexus5上面的顯示效果就是下面這樣

但是如果在Nexus S或者是Nexus One運行呢?下面是運行結果

可以看到,兩個按鈕發生了重疊。
我們都已經用了dp了,為什么會出現這種情況呢?
你聽我慢慢道來。
雖然說dp可以去除不同像素密度的問題,使得1dp在不同像素密度上面的顯示效果相同,但是還是由于Android屏幕設備的多樣性,如果使用dp來作為度量單位,并不是所有的屏幕的寬度都是相同的dp長度,比如說,Nexus S和Nexus One屬于hdpi,屏幕寬度是320dp,而Nexus 5屬于xxhdpi,屏幕寬度是360dp,Galaxy Nexus屬于xhdpi,屏幕寬度是384dp,Nexus 6 屬于xxxhdpi,屏幕寬度是410dp。所以說,光Google自己一家的產品就已經有這么多的標準,而且屏幕寬度和像素密度沒有任何關聯關系,即使我們使用dp,在320dp寬度的設備和410dp的設備上,還是會有90dp的差別。當然,我們盡量使用match_parent和wrap_content,盡可能少的用dp來指定控件的具體長寬,再結合上權重,大部分的情況我們都是可以做到適配的。

但是除了這個方法,我們還有沒有其他的更徹底的解決方案呢?
我們換另外一個思路來思考這個問題。
*下面的方案來自Android Day Day Up 一群的【blue-深圳】,謝謝他的分享精神*
因為分辨率不一樣,所以不能用px;因為屏幕寬度不一樣,所以要小心的用dp,那么我們可不可以用另外一種方法來統一單位,不管分辨率是多大,屏幕寬度用一個固定的值的單位來統計呢?
答案是:當然可以。
我們假設手機屏幕的寬度都是320某單位,那么我們將一個屏幕寬度的總像素數平均分成320份,每一份對應具體的像素就可以了。
具體如何來實現呢?我們看下面的代碼
~~~
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
public class MakeXml {
private final static String rootPath = "C:\\Users\\Administrator\\Desktop\\layoutroot\\values-{0}x{1}\\";
private final static float dw = 320f;
private final static float dh = 480f;
private final static String WTemplate = "<dimen name=\"x{0}\">{1}px</dimen>\n";
private final static String HTemplate = "<dimen name=\"y{0}\">{1}px</dimen>\n";
public static void main(String[] args) {
makeString(320, 480);
makeString(480,800);
makeString(480, 854);
makeString(540, 960);
makeString(600, 1024);
makeString(720, 1184);
makeString(720, 1196);
makeString(720, 1280);
makeString(768, 1024);
makeString(800, 1280);
makeString(1080, 1812);
makeString(1080, 1920);
makeString(1440, 2560);
}
public static void makeString(int w, int h) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
sb.append("<resources>");
float cellw = w / dw;
for (int i = 1; i < 320; i++) {
sb.append(WTemplate.replace("{0}", i + "").replace("{1}",
change(cellw * i) + ""));
}
sb.append(WTemplate.replace("{0}", "320").replace("{1}", w + ""));
sb.append("</resources>");
StringBuffer sb2 = new StringBuffer();
sb2.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
sb2.append("<resources>");
float cellh = h / dh;
for (int i = 1; i < 480; i++) {
sb2.append(HTemplate.replace("{0}", i + "").replace("{1}",
change(cellh * i) + ""));
}
sb2.append(HTemplate.replace("{0}", "480").replace("{1}", h + ""));
sb2.append("</resources>");
String path = rootPath.replace("{0}", h + "").replace("{1}", w + "");
File rootFile = new File(path);
if (!rootFile.exists()) {
rootFile.mkdirs();
}
File layxFile = new File(path + "lay_x.xml");
File layyFile = new File(path + "lay_y.xml");
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
pw.print(sb.toString());
pw.close();
pw = new PrintWriter(new FileOutputStream(layyFile));
pw.print(sb2.toString());
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static float change(float a) {
int temp = (int) (a * 100);
return temp / 100f;
}
}
~~~
代碼應該很好懂,我們將一個屏幕寬度分為320份,高度480份,然后按照實際像素對每一個單位進行復制,放在對應values-widthxheight文件夾下面的lax.xml和lay.xml里面,這樣就可以統一所有你想要的分辨率的單位了,下面是生成的一個320*480分辨率的文件,因為寬高分割之后總分數和像素數相同,所以x1就是1px,以此類推
~~~
<?xml version="1.0" encoding="utf-8"?>
<resources><dimen name="x1">1.0px</dimen>
<dimen name="x2">2.0px</dimen>
<dimen name="x3">3.0px</dimen>
<dimen name="x4">4.0px</dimen>
<dimen name="x5">5.0px</dimen>
<dimen name="x6">6.0px</dimen>
<dimen name="x7">7.0px</dimen>
<dimen name="x8">8.0px</dimen>
<dimen name="x9">9.0px</dimen>
<dimen name="x10">10.0px</dimen>
...省略好多行
<dimen name="x300">300.0px</dimen>
<dimen name="x301">301.0px</dimen>
<dimen name="x302">302.0px</dimen>
<dimen name="x303">303.0px</dimen>
<dimen name="x304">304.0px</dimen>
<dimen name="x305">305.0px</dimen>
<dimen name="x306">306.0px</dimen>
<dimen name="x307">307.0px</dimen>
<dimen name="x308">308.0px</dimen>
<dimen name="x309">309.0px</dimen>
<dimen name="x310">310.0px</dimen>
<dimen name="x311">311.0px</dimen>
<dimen name="x312">312.0px</dimen>
<dimen name="x313">313.0px</dimen>
<dimen name="x314">314.0px</dimen>
<dimen name="x315">315.0px</dimen>
<dimen name="x316">316.0px</dimen>
<dimen name="x317">317.0px</dimen>
<dimen name="x318">318.0px</dimen>
<dimen name="x319">319.0px</dimen>
<dimen name="x320">320px</dimen>
</resources>
~~~
那么1080*1960分辨率下是什么樣子呢?我們可以看下,由于1080和320是3.37倍的關系,所以x1=3.37px
~~~
<?xml version="1.0" encoding="utf-8"?>
<resources><dimen name="x1">3.37px</dimen>
<dimen name="x2">6.75px</dimen>
<dimen name="x3">10.12px</dimen>
<dimen name="x4">13.5px</dimen>
<dimen name="x5">16.87px</dimen>
<dimen name="x6">20.25px</dimen>
<dimen name="x7">23.62px</dimen>
<dimen name="x8">27.0px</dimen>
<dimen name="x9">30.37px</dimen>
<dimen name="x10">33.75px</dimen>
...省略好多行
<dimen name="x300">1012.5px</dimen>
<dimen name="x301">1015.87px</dimen>
<dimen name="x302">1019.25px</dimen>
<dimen name="x303">1022.62px</dimen>
<dimen name="x304">1026.0px</dimen>
<dimen name="x305">1029.37px</dimen>
<dimen name="x306">1032.75px</dimen>
<dimen name="x307">1036.12px</dimen>
<dimen name="x308">1039.5px</dimen>
<dimen name="x309">1042.87px</dimen>
<dimen name="x310">1046.25px</dimen>
<dimen name="x311">1049.62px</dimen>
<dimen name="x312">1053.0px</dimen>
<dimen name="x313">1056.37px</dimen>
<dimen name="x314">1059.75px</dimen>
<dimen name="x315">1063.12px</dimen>
<dimen name="x316">1066.5px</dimen>
<dimen name="x317">1069.87px</dimen>
<dimen name="x318">1073.25px</dimen>
<dimen name="x319">1076.62px</dimen>
<dimen name="x320">1080px</dimen>
</resources>
~~~
無論在什么分辨率下,x320都是代表屏幕寬度,y480都是代表屏幕高度。
那么,我們應該如何使用呢?
首先,我們要把生成的所有values文件夾放到res目錄下,當設計師把UI高清設計圖給你之后,你就可以根據設計圖上的尺寸,以某一個分辨率的機型為基礎,找到對應像素數的單位,然后設置給控件即可。
下圖還是兩個Button,不同的是,我們把單位換成了我們在values文件夾下dimen的值,這樣在你指定的分辨率下,不管寬度是320dp、360dp,還是410dp,就都可以完全適配了。

但是,還是有個問題,為什么下面的三個沒有適配呢?
這是因為由于在生成的values文件夾里,沒有對應的分辨率,其實一開始是報錯的,因為默認的values沒有對應dimen,所以我只能在默認values里面也創建對應文件,但是里面的數據卻不好處理,因為不知道分辨率,我只好默認為x1=1dp保證盡量兼容。這也是這個解決方案的幾個弊端,對于沒有生成對應分辨率文件的手機,會使用默認values文件夾,如果默認文件夾沒有,就會出現問題。
所以說,這個方案雖然是一勞永逸,但是由于實際上還是使用的px作為長度的度量單位,所以多少和google的要求有所背離,不好說以后會不會出現什么不可預測的問題。其次,如果要使用這個方案,你必須盡可能多的包含所有的分辨率,因為這個是使用這個方案的基礎,如果有分辨率缺少,會造成顯示效果很差,甚至出錯的風險,而這又勢必會增加軟件包的大小和維護的難度,所以大家自己斟酌,擇優使用。
更多信息可參考鴻洋的新文章[Android 屏幕適配方案](http://blog.csdn.net/lmj623565791/article/details/45460089)
### 提供備用位圖
由于 Android 可在具有各種屏幕密度的設備上運行,因此我們提供的位圖資源應始終可以滿足各類普遍密度范圍的要求:低密度、中等密度、高密度以及超高密度。這將有助于我們的圖片在所有屏幕密度上都能得到出色的質量和效果。
要生成這些圖片,我們應先提取矢量格式的原始資源,然后根據以下尺寸范圍針對各密度生成相應的圖片。
* xhdpi:2.0
* hdpi:1.5
* mdpi:1.0(最低要求)
* ldpi:0.75
也就是說,如果我們為 xhdpi 設備生成了 200x200 px尺寸的圖片,就應該使用同一資源為 hdpi、mdpi 和 ldpi 設備分別生成 150x150、100x100 和 75x75 尺寸的圖片。
然后,將生成的圖片文件放在 res/ 下的相應子目錄中(mdpi、hdpi、xhdpi、xxhdpi),系統就會根據運行您應用的設備的屏幕密度自動選擇合適的圖片。
這樣一來,只要我們引用 @drawable/id,系統都能根據相應屏幕的 dpi 選取合適的位圖。
還記得我們上面提到的圖標設計尺寸嗎?和這個其實是一個意思。
但是還有個問題需要注意下,如果是.9圖或者是不需要多個分辨率的圖片,就放在drawable文件夾即可,對應分辨率的圖片要正確的放在合適的文件夾,否則會造成圖片拉伸等問題。
## 實施自適應用戶界面流程
前面我們介紹過,如何根據設備特點顯示恰當的布局,但是這樣做,會使得用戶界面流程可能會有所不同。例如,如果應用處于雙面板模式下,點擊左側面板上的項即可直接在右側面板上顯示相關內容;而如果該應用處于單面板模式下,點擊相關的內容應該跳轉到另外一個Activity進行后續的處理。所以我們應該按照下面的流程,一步步的完成自適應界面的實現。
### 確定當前布局
由于每種布局的實施都會稍有不同,因此我們需要先確定當前向用戶顯示的布局。例如,我們可以先了解用戶所處的是“單面板”模式還是“雙面板”模式。要做到這一點,可以通過查詢指定視圖是否存在以及是否已顯示出來。
~~~
public class NewsReaderActivity extends FragmentActivity {
boolean mIsDualPane;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
View articleView = findViewById(R.id.article);
mIsDualPane = articleView != null &&
articleView.getVisibility() == View.VISIBLE;
}
}
~~~
請注意,這段代碼用于查詢“報道”面板是否可用,與針對具體布局的硬編碼查詢相比,這段代碼的靈活性要大得多。
再舉一個適應各種組件的存在情況的方法示例:在對這些組件執行操作前先查看它們是否可用。例如,新聞閱讀器示例應用中有一個用于打開菜單的按鈕,但只有在版本低于 3.0 的 Android 上運行該應用時,這個按鈕才會存在,因為 API 級別 11 或更高級別中的 ActionBar 已取代了該按鈕的功能。因此,您可以使用以下代碼為此按鈕添加事件偵聽器:
~~~
Button catButton = (Button) findViewById(R.id.categorybutton);
OnClickListener listener = /* create your listener here */;
if (catButton != null) {
catButton.setOnClickListener(listener);
}
~~~
### 根據當前布局做出響應
有些操作可能會因當前的具體布局而產生不同的結果。例如,在新聞閱讀器示例中,如果用戶界面處于雙面板模式下,那么點擊標題列表中的標題就會在右側面板中打開相應報道;但如果用戶界面處于單面板模式下,那么上述操作就會啟動一個獨立活動:
~~~
@Override
public void onHeadlineSelected(int index) {
mArtIndex = index;
if (mIsDualPane) {
/* display article on the right pane */
mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
} else {
/* start a separate activity */
Intent intent = new Intent(this, ArticleActivity.class);
intent.putExtra("catIndex", mCatIndex);
intent.putExtra("artIndex", index);
startActivity(intent);
}
}
~~~
同樣,如果該應用處于雙面板模式下,就應設置帶導航標簽的操作欄;但如果該應用處于單面板模式下,就應使用下拉菜單設置導航欄。因此我們的代碼還應確定哪種情況比較合適:
~~~
final String CATEGORIES[] = { "熱門報道", "政治", "經濟", "Technology" };
public void onCreate(Bundle savedInstanceState) {
....
if (mIsDualPane) {
/* use tabs for navigation */
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
int i;
for (i = 0; i < CATEGORIES.length; i++) {
actionBar.addTab(actionBar.newTab().setText(
CATEGORIES[i]).setTabListener(handler));
}
actionBar.setSelectedNavigationItem(selTab);
}
else {
/* use list navigation (spinner) */
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
SpinnerAdapter adap = new ArrayAdapter(this,
R.layout.headline_item, CATEGORIES);
actionBar.setListNavigationCallbacks(adap, handler);
}
}
~~~
### 重復使用其他活動中的片段
多屏幕設計中的重復模式是指,對于某些屏幕配置,已實施界面的一部分會用作面板;但對于其他配置,這部分就會以獨立活動的形式存在。例如,在新聞閱讀器示例中,對于較大的屏幕,新聞報道文本會顯示在右側面板中;但對于較小的屏幕,這些文本就會以獨立活動的形式存在。
在類似情況下,通常可以在多個活動中重復使用相同的 Fragment 子類以避免代碼重復。例如,在雙面板布局中使用了 ArticleFragment:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
~~~
然后又在小屏幕的Activity布局中重復使用了它 :
~~~
ArticleFragment frag = new ArticleFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
~~~
當然,這與在 XML 布局中聲明片段的效果是一樣的,但在這種情況下卻沒必要使用 XML 布局,因為報道片段是此活動中的唯一組件。
請務必在設計片段時注意,不要針對具體活動創建強耦合。要做到這一點,通常可以定義一個接口,該接口概括了相關片段與其主活動交互所需的全部方式,然后讓主活動實施該界面:
例如,新聞閱讀器應用的 HeadlinesFragment 會精確執行以下代碼:
~~~
public class HeadlinesFragment extends ListFragment {
...
OnHeadlineSelectedListener mHeadlineSelectedListener = null;
/* Must be implemented by host activity */
public interface OnHeadlineSelectedListener {
public void onHeadlineSelected(int index);
}
...
public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
mHeadlineSelectedListener = listener;
}
}
~~~
然后,如果用戶選擇某個標題,相關片段就會通知由主活動指定的偵聽器(而不是通知某個硬編碼的具體活動):
~~~
public class HeadlinesFragment extends ListFragment {
...
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (null != mHeadlineSelectedListener) {
mHeadlineSelectedListener.onHeadlineSelected(position);
}
}
...
}
~~~
除此之外,我們還可以使用第三方框架,比如說使用“訂閱-發布”模式的EventBus來更多的優化組件之間的通信,減少耦合。
### 處理屏幕配置變化
如果我們使用獨立Activity實施界面的獨立部分,那么請注意,我們可能需要對特定配置變化(例如屏幕方向的變化)做出響應,以便保持界面的一致性。
例如,在運行 Android 3.0 或更高版本的標準 7 英寸平板電腦上,如果新聞閱讀器示例應用運行在縱向模式下,就會在使用獨立活動顯示新聞報道;但如果該應用運行在橫向模式下,就會使用雙面板布局。
也就是說,如果用戶處于縱向模式下且屏幕上顯示的是用于閱讀報道的活動,那么就需要在檢測到屏幕方向變化(變成橫向模式)后執行相應操作,即停止上述活動并返回主活動,以便在雙面板布局中顯示相關內容:
~~~
public class ArticleActivity extends FragmentActivity {
int mCatIndex, mArtIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
// If should be in two-pane mode, finish to return to main activity
if (getResources().getBoolean(R.bool.has_two_panes)) {
finish();
return;
}
...
}
~~~
通過上面幾個步驟,我們就完全可以建立一個可以根據用戶界面配置進行自適應的App了。
## 最佳實踐
### 關于高清設計圖尺寸
Google官方給出的高清設計圖尺寸有兩種方案,一種是以mdpi設計,然后對應放大得到更高分辨率的圖片,另外一種則是以高分辨率作為設計大小,然后按照倍數對應縮小到小分辨率的圖片。
根據經驗,我更推薦第二種方法,因為小分辨率在生成高分辨率圖片的時候,會出現像素丟失,我不知道是不是有方法可以阻止這種情況發生。
而分辨率可以以1280*720或者是1960*1080作為主要分辨率進行設計。
### ImageView的ScaleType屬性
設置不同的ScaleType會得到不同的顯示效果,一般情況下,設置為centerCrop能獲得較好的適配效果。
### 動態設置
有一些情況下,我們需要動態的設置控件大小或者是位置,比如說popwindow的顯示位置和偏移量等,這個時候我們可以動態的獲取當前的屏幕屬性,然后設置合適的數值
~~~
public class ScreenSizeUtil {
public static int getScreenWidth(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getWidth();
}
public static int getScreenHeight(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getHeight();
}
}
~~~
## 更多參考資料
* [chan奕迅(設計師角度)](http://www.zcool.com.cn/u/360473)
* [友盟移動指數(最新的移動設備統計信息)](http://www.umindex.com/devices/android_models)
* [手機屏幕信息大全](http://screensiz.es/phone)