最近在学习郭霖大神的第一行代码,闲来看看哪儿的基础不扎实,补补。收获多多。
今天随手记下手机和平板的适配要点:
- 两种布局文件夹: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里所以不管是手机还是平板一套代码就够了。