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

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

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

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

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

          

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

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

首先你须要对Fragment有必定的了解,若是你还没接触过Fragment,建议能够先阅读 Android Fragment彻底解析,关于碎片你所需知道的一切 这篇文章。而且本次的代码是运行在Android 4.0版本上的,若是你的SDK版本还比较低的话,建议能够先升升级了。 this

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

  1. public class MainActivity extends Activity { 
  2.  
  3.     @Override 
  4.     public void onCreate(Bundle savedInstanceState) { 
  5.         super.onCreate(savedInstanceState); 
  6.         setContentView(R.layout.activity_main); 
  7.     } 
  8.  

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做为程序的主布局文件,里面代码以下: .net

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://schemas.android.com/tools" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" 
  5.     android:orientation="horizontal" 
  6.     tools:context=".MainActivity" > 
  7.  
  8.     <fragment 
  9.         android:id="@+id/menu_fragment" 
  10.         android:name="com.example.fragmentdemo.MenuFragment" 
  11.         android:layout_width="fill_parent" 
  12.         android:layout_height="fill_parent" 
  13.         /> 
  14.  
  15. </LinearLayout> 

<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,加入以下代码: code

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     xmlns:tools="http://schemas.android.com/tools" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" 
  5.     android:orientation="horizontal" 
  6.     android:baselineAligned="false" 
  7.     tools:context=".MainActivity" 
  8.     > 
  9.  
  10.     <fragment 
  11.         android:id="@+id/left_fragment" 
  12.         android:name="com.example.fragmentdemo.MenuFragment" 
  13.         android:layout_width="0dip" 
  14.         android:layout_height="fill_parent" 
  15.         android:layout_weight="1" 
  16.         /> 
  17.      
  18.     <FrameLayout  
  19.         android:id="@+id/details_layout" 
  20.         android:layout_width="0dip" 
  21.         android:layout_height="fill_parent" 
  22.         android:layout_weight="3" 
  23.         ></FrameLayout> 
  24.  
  25. </LinearLayout> 

<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用于显示详细内容。其实也就是分别对应了平板界面上的左侧布局和右侧布局。 xml

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

关于动态加载布局的更多内容,能够阅读 Android官方提供的支持不一样屏幕大小的所有方法 这篇文章。

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

  1. public class MenuFragment extends Fragment implements OnItemClickListener { 
  2.  
  3.     /** 
  4.      * 菜单界面中只包含了一个ListView。
  5.      */ 
  6.     private ListView menuList; 
  7.  
  8.     /** 
  9.      * ListView的适配器。
  10.      */ 
  11.     private ArrayAdapter<String> adapter; 
  12.  
  13.     /** 
  14.      * 用于填充ListView的数据,这里就简单只用了两条数据。
  15.      */ 
  16.     private String[] menuItems = { "Sound", "Display" }; 
  17.  
  18.     /** 
  19.      * 是不是双页模式。若是一个Activity中包含了两个Fragment,就是双页模式。
  20.      */ 
  21.     private boolean isTwoPane; 
  22.  
  23.     /** 
  24.      * 当Activity和Fragment创建关联时,初始化适配器中的数据。
  25.      */ 
  26.     @Override 
  27.     public void onAttach(Activity activity) { 
  28.         super.onAttach(activity); 
  29.         adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems); 
  30.     } 
  31.  
  32.     /** 
  33.      * 加载menu_fragment布局文件,为ListView绑定了适配器,并设置了监听事件。
  34.      */ 
  35.     @Override 
  36.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  37.         View view = inflater.inflate(R.layout.menu_fragment, container, false); 
  38.         menuList = (ListView) view.findViewById(R.id.menu_list); 
  39.         menuList.setAdapter(adapter); 
  40.         menuList.setOnItemClickListener(this); 
  41.         return view; 
  42.     } 
  43.  
  44.     /** 
  45.      * 当Activity建立完毕后,尝试获取一下布局文件中是否有details_layout这个元素,若是有说明当前
  46.      * 是双页模式,若是没有说明当前是单页模式。
  47.      */ 
  48.     @Override 
  49.     public void onActivityCreated(Bundle savedInstanceState) { 
  50.         super.onActivityCreated(savedInstanceState); 
  51.         if (getActivity().findViewById(R.id.details_layout) != null) { 
  52.             isTwoPane = true
  53.         } else
  54.             isTwoPane = false
  55.         } 
  56.     } 
  57.  
  58.     /** 
  59.      * 处理ListView的点击事件,会根据当前是不是双页模式进行判断。若是是双页模式,则会动态添加Fragment。
  60.      * 若是不是双页模式,则会打开新的Activity。
  61.      */ 
  62.     @Override 
  63.     public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) { 
  64.         if (isTwoPane) { 
  65.             Fragment fragment = null
  66.             if (index == 0) { 
  67.                 fragment = new SoundFragment(); 
  68.             } else if (index == 1) { 
  69.                 fragment = new DisplayFragment(); 
  70.             } 
  71.             getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit(); 
  72.         } else
  73.             Intent intent = null
  74.             if (index == 0) { 
  75.                 intent = new Intent(getActivity(), SoundActivity.class); 
  76.             } else if (index == 1) { 
  77.                 intent = new Intent(getActivity(), DisplayActivity.class); 
  78.             } 
  79.             startActivity(intent); 
  80.         } 
  81.     } 
  82.  

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文件,加入以下代码:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" > 
  5.      
  6.     <ListView 
  7.         android:id="@+id/menu_list" 
  8.         android:layout_width="fill_parent" 
  9.         android:layout_height="fill_parent" 
  10.         ></ListView> 
  11.  
  12. </LinearLayout> 

<?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" >
    
    <ListView
        android:id="@+id/menu_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        ></ListView>

</LinearLayout>

而后新建SoundFragment,里面内容很是简单:
  1. public class SoundFragment extends Fragment { 
  2.  
  3.     @Override 
  4.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  5.         View view = inflater.inflate(R.layout.sound_fragment, container, false); 
  6.         return view; 
  7.     } 
  8.  

public class SoundFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.sound_fragment, container, false);
		return view;
	}

}

这里SoundFragment须要用到sound_fragment.xml布局文件,所以这里咱们新建这个布局文件,并加入以下代码:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:background="#00ff00" 
  6.     android:orientation="vertical" > 
  7.      
  8.     <TextView  
  9.         android:layout_width="wrap_content" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_centerInParent="true" 
  12.         android:textSize="28sp" 
  13.         android:textColor="#000000" 
  14.         android:text="This is sound view" 
  15.         /> 
  16.  
  17. </RelativeLayout> 

<?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布局文件:
  1. public class DisplayFragment extends Fragment { 
  2.  
  3.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
  4.         View view = inflater.inflate(R.layout.display_fragment, container, false); 
  5.         return view; 
  6.     } 

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;
	}
}

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:background="#0000ff" 
  6.     android:orientation="vertical" > 
  7.      
  8.     <TextView  
  9.         android:layout_width="wrap_content" 
  10.         android:layout_height="wrap_content" 
  11.         android:layout_centerInParent="true" 
  12.         android:textSize="28sp" 
  13.         android:textColor="#000000" 
  14.         android:text="This is display view" 
  15.         /> 
  16.  
  17. </RelativeLayout> 

<?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,代码以下:
  1. public class SoundActivity extends Activity { 
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) { 
  5.         super.onCreate(savedInstanceState); 
  6.         setContentView(R.layout.sound_activity); 
  7.     } 
  8.  

public class SoundActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sound_activity);
	}

}

这个Activity只是加载了一个布局文件,如今咱们来实现sound_activity.xml这个布局文件:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:id="@+id/sound_fragment" 
  4.     android:name="com.example.fragmentdemo.SoundFragment" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="match_parent" > 
  7.  
  8. </fragment> 

<?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:

  1. public class DisplayActivity extends Activity { 
  2.  
  3.     @Override 
  4.     protected void onCreate(Bundle savedInstanceState) { 
  5.         super.onCreate(savedInstanceState); 
  6.         setContentView(R.layout.display_activity); 
  7.     } 
  8.  

public class DisplayActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_activity);
	}

}

而后加入display_activity.xml:
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:id="@+id/display_fragment" 
  4.     android:name="com.example.fragmentdemo.DisplayFragment" 
  5.     android:layout_width="match_parent" 
  6.     android:layout_height="match_parent" > 
  7.  
  8. </fragment> 

<?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,更多复杂的内容须要你们本身去实现了。

相关文章
相关标签/搜索