今天看啥  ›  专栏  ›  郭霖

Android手机平板两不误,使用Fragment实现兼容手机和平板的程序

郭霖  · 掘金  ·  · 2021-04-07 11:47
阅读 9

Android手机平板两不误,使用Fragment实现兼容手机和平板的程序

记得我之前参与开发过一个华为的项目,要求程序可以支持好几种终端设备,其中就包括 Android 手机和 Android Pad。然后为了节省人力,公司无节操地让 Android 手机和 Android Pad 都由我们团队开发。当时项目组定的方案是,制作两个版本的 App,一个手机版,一个 Pad 版。由于当时手机版的主体功能已经做的差不多了,所以 Pad 版基本上就是把手机版的代码完全拷过来,然后再根据平板的特性部分稍作修改就好了。

但是,从此以后我们就非常苦逼了。每次要添加什么新功能,同样的代码要写两遍。每次要修复任何 bug,都要在手机版代码和 Pad 版代码里各修改一遍。这还不算什么,每到出版本的时候就更离谱了。华为要求每次需要出两个版本,一个华为内网环境的版本,一个客户现场的版本,而现在又分了手机和 Pad,也就是每次需要出四个版本。如果在出完版本后自测还出现了问题,就可以直接通宵了。这尤其是苦了我们的 X 总 (由于他 dota 打的比较好,我都喜欢叫他 X 神)。他在我们项目组中单独维护一个模块,并且每次打版本都是由他负责,加班的时候我们都能跑,就是他跑不了。这里也是赞扬一下我们 X 神的敬业精神,如果他看得到的话。

经历过那么苦逼时期的我也就开始思考,可不可以制作同时兼容手机和平板的 App 呢?答案当然是肯定的,不过我这个人比较懒,一直也提不起精神去钻研这个问题。直到我一个在美国留学的朋友 Gong 让我帮她解决她的研究生导师布置的作业 (我知道你研究生导师看不懂中文 ^-^),正好涉及到了这一块,也就借此机会研究了一下,现在拿出来跟大家分享。

我们先来看一下 Android 手机的设置界面,点击一下 Sound,可以跳转到声音设置界面,如下面两张图所示:

           

然后再来看一下 Android Pad 的设置界面,主设置页面和声音设置页面都是在一个界面显示的,如下图所示:

如果这分别是两个不同的 App 做出的效果,那没有丝毫惊奇之处。但如果是同一个 App,在手机上和平板上运行分别有以上两种效果的话,你是不是就已经心动了?我们现在就来模拟实现一下。

首先你需要对 Fragment 有一定的了解,如果你还没接触过 Fragment,建议可以先阅读 Android Fragment 完全解析,关于碎片你所需知道的一切 这篇文章。并且本次的代码是运行在 Android 4.0 版本上的,如果你的 SDK 版本还比较低的话,建议可以先升升级了。

新建一个 Android 项目,取名叫 FragmentDemo。打开或新建 MainActivity 作为程序的主 Activity,里面有如下自动生成的内容:

public class MainActivity extends Activity {
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
 
}
复制代码

作为一个 Android 老手,上面的代码实在太小儿科了,每个 Activity 中都会有这样的代码。不过今天我们的程序可不会这么简单,加载布局这一块还是大有文章的。

打开或新建 res/layout/activity_main.xml 作为程序的主布局文件,里面代码如下:

<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.example.fragmentdemo.MenuFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />
 
</LinearLayout>
复制代码

这个布局引用了一个 MenuFragment,我们稍后来进行实现,先来看一下今天的一个重点,我们需要再新建一个 activity_main.xml,这个布局文件名和前面的主布局文件名是一样的,但是要放在不同的目录下面。

在 res 目录下新建 layout-large 目录,然后这个目录下创建新的 activity_main.xml,加入如下代码:

<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.example.fragmentdemo.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>
复制代码

这个布局同样也引用了 MenuFragment,另外还加入了一个 FrameLayout 用于显示详细内容。其实也就是分别对应了平板界面上的左侧布局和右侧布局。

这里用到了动态加载布局的技巧,首先 Activity 中调用 setContentView(R.layout.activity_main) ,表明当前的 Activity 想加载 activity_main 这个布局文件。而 Android 系统又会根据当前的运行环境判断程序是否运行在大屏幕设备上,如果运行在大屏幕设备上,就加载 layout-large 目录下的 activity_main.xml,否则就默认加载 layout 目录下的 activity_main.xml。

关于动态加载布局的更多内容,可以阅读 Android 官方提供的支持不同屏幕大小的全部方法 这篇文章。

下面我们来实现久违的 MenuFragment,新建一个 MenuFragment 类继承自 Fragment,具体代码如下:

public class MenuFragment extends Fragment implements OnItemClickListener {
 
	/**
	 * 菜单界面中只包含了一个ListView。
	 */
	private ListView menuList;
 
	/**
	 * ListView的适配器。
	 */
	private ArrayAdapter<String> adapter;
 
	/**
	 * 用于填充ListView的数据,这里就简单只用了两条数据。
	 */
	private String[] menuItems = { "Sound", "Display" };
 
	/**
	 * 是否是双页模式。如果一个Activity中包含了两个Fragment,就是双页模式。
	 */
	private boolean isTwoPane;
 
	/**
	 * 当Activity和Fragment建立关联时,初始化适配器中的数据。
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems);
	}
 
	/**
	 * 加载menu_fragment布局文件,为ListView绑定了适配器,并设置了监听事件。
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.menu_fragment, container, false);
		menuList = (ListView) view.findViewById(R.id.menu_list);
		menuList.setAdapter(adapter);
		menuList.setOnItemClickListener(this);
		return view;
	}
 
	/**
	 * 当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);
		}
	}
 
}
复制代码

这个类的代码并不长,我简单的说明一下。在 onCreateView 方法中加载了 menu_fragment 这个布局,这个布局里面包含了一个 ListView,然后我们对这个 ListView 填充了两个简单的数据 "Sound" 和 "Display" 。又在 onActivityCreated 方法中做了一个判断,如果 Activity 的布局中包含了 details_layout 这个元素,那么当前就是双页模式,否则就是单页模式。onItemClick 方法则处理了 ListView 的点击事件,发现如果当前是双页模式,就动态往 details_layout 中添加 Fragment,如果当前是单页模式,就直接打开新的 Activity。

我们把 MenuFragment 中引用到的其它内容一个个添加进来。新建 menu_fragment.xml 文件,加入如下代码:

<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

android:id="@+id/menu_list"

android:layout_width="fill_parent"

android:layout_height="fill_parent"
复制代码

然后新建 SoundFragment,里面内容非常简单:

public class SoundFragment extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.sound_fragment, container, false);
复制代码

这里 SoundFragment 需要用到 sound_fragment.xml 布局文件,因此这里我们新建这个布局文件,并加入如下代码:

<?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"
    android:background="#00ff00"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="28sp"
        android:textColor="#000000"
        android:text="This is sound view"
        />
 
</RelativeLayout>
复制代码

同样的道理,我们再新建 DisplayFragment 和 display_fragment.xml 布局文件:

public class DisplayFragment extends Fragment {
 
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.display_fragment, container, false);
		return view;
	}
}
复制代码
<?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"
    android:background="#0000ff"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="28sp"
        android:textColor="#000000"
        android:text="This is display view"
        />
 
</RelativeLayout>
复制代码

然后新建 SoundActivity,代码如下:

public class SoundActivity extends Activity {
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sound_activity);
	}
 
}
复制代码

这个 Activity 只是加载了一个布局文件,现在我们来实现 sound_activity.xml 这个布局文件:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sound_fragment"
    android:name="com.example.fragmentdemo.SoundFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
</fragment>
复制代码

这个布局文件引用了 SoundFragment,这样写的好处就是,以后我们只需要在 SoundFragment 中修改代码,SoundActivity 就会跟着自动改变了,因为它所有的代码都是从 SoundFragment 中引用过来的。

好,同样的方法,我们再完成 DisplayActivity:

public class DisplayActivity extends Activity {
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_activity);
	}
 
}
复制代码

然后加入 display_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/display_fragment"
    android:name="com.example.fragmentdemo.DisplayFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
</fragment>
复制代码

现在所有的代码就都已经完成了,我们来看一下效果吧。

首先将程序运行在手机上,效果图如下:

分别点击 Sound 和 Display,界面会跳转到声音和显示界面:

           

然后将程序在平板上运行,点击 Sound,效果图如下:

然后点击 Display 切换到显示界面,效果图如下:

这样我们就成功地让程序同时兼容手机和平板了。当然,这只是一个简单的 demo,更多复杂的内容需要大家自己去实现了。

好了,今天的讲解到此结束,有疑问的朋友请在下面留言。

源码下载,请点击这里

关注我的技术公众号“郭霖”,每天都有优质技术文章推送。




原文地址:访问原文地址
快照地址: 访问文章快照