最近在學習郭霖大神的第一行代碼,閒來看看哪兒的基礎不紮實,補補。收穫多多。
今天隨手記下手機和平板的適配要點:
- 兩種佈局文件夾:layout及layout-large注意不是下劃線是橫線
- 判斷當前是手機還是平板
- 根據當前屏幕代碼操作不同
效果
兩個佈局
- layout文件夾下默認佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<fragment
android:id="@+id/menu_fragment"
android:name="com.yuanli.myapplication.MenuFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
- layout-large文件夾下的大屏佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:baselineAligned="false"
tools:context=".MainActivity"
>
<fragment
android:id="@+id/left_fragment"
android:name="com.yuanli.myapplication.MenuFragment"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
<FrameLayout
android:id="@+id/details_layout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="3"
></FrameLayout>
</LinearLayout>
- 什麼是large?
這裏的large是系統認定的,就像我們平時建圖片文件後面加-large一樣。Android 3.2 版本引入了最小寬度限定符(Smallest-width Qualifier):允許我們對屏幕寬度指定一個最小值(dp爲單位)。大於它加載一個佈局,小於加載另一個。此時另一種佈局的文件名要變一下,
變成:layout-sw600dp。意爲:屏幕寬度大於600dp的設備加載這個文件中的佈局,小於的加載默認layout中的佈局。
判斷當前屏幕
根據兩種佈局包含的內容不同來區分,要在activity創建完成後判斷。
/**
* 是否是雙頁模式。如果一個Activity中包含了兩個Fragment,就是雙頁模式。
*/
private boolean isTwoPane;
/**
* 當Activity創建完畢後,嘗試獲取一下佈局文件中是否有details_layout這個元素,如果有說明當前
* 是雙頁模式,如果沒有說明當前是單頁模式。
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.details_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
操作不同
/**
* 處理ListView的點擊事件,會根據當前是否是雙頁模式進行判斷。如果是雙頁模式,則會動態添加Fragment。
* 如果不是雙頁模式,則會打開新的Activity。
*/
@Override
public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
if (isTwoPane) {
Fragment fragment = null;
if (index == 0) {
fragment = new SoundFragment();
} else if (index == 1) {
fragment = new DisplayFragment();
}
getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit();
} else {
Intent intent = null;
if (index == 0) {
intent = new Intent(getActivity(), SoundActivity.class);
} else if (index == 1) {
intent = new Intent(getActivity(), DisplayActivity.class);
}
startActivity(intent);
}
}
因爲最終邏輯都寫在SoundFragment、DisplayFragment裏所以不管是手機還是平板一套代碼就夠了。