Fragment同时适配手机和平板两种屏幕

来源:互联网 发布:js中播放器代码 编辑:程序博客网 时间:2024/05/17 04:44


       Fragment对于Android开发来说,是一个必不可少的工具,我们使用这个工具可以轻松应对很多界面管理上的问题,例如如何分屏,如何移除界面和替换界面等。更为神奇的是,我们可以结合Android系统的特性和Fragment来实现一个工程适应手机平板两种屏幕。当然这需要我们在代码中进行一点判断。现在,通过下面这个例子我们来了解一下如何用同一个工程来适应手机和平板的。

      首先,我们需要看一下目录结构,这次的目录结构要比前两次的目录复杂一些。主要原因是这次除了需要主Activity的布局之外还需要Fragment的布局。


         

       要看出平板和手机的效果需要两个Fragment,这样如果是手机的话就会从一个Fragment跳转到另一个Fragment,如果是平板的话就会在同一个屏幕上显示出两个Fragment。

       这里实现依赖Android系统的限定符,也就是类似layout-land的形式,“-”后面跟的就是限定符,限定符是用来提示系统需要加载内容的,比如这里,如果是横向的屏幕时就会加载这里的布局文件。

      接下来奉上详细代码,因为是手机和平板两个版本,所以会有两个Activity布局。

手机版布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >        <!-- 装载列表的Fragment 的容器 -->    <LinearLayout         android:id="@+id/list_container"        android:orientation="vertical"        android:layout_width="match_parent"  android:layout_height="match_parent">    </LinearLayout>            <!-- 装载详情的Fragment 的容器 -->    <LinearLayout         android:id="@+id/detail_container"        android:orientation="vertical"        android:layout_width="match_parent"  android:layout_height="match_parent">    </LinearLayout></FrameLayout>

      这是在一个FrameLayout下放置了两个LinearLayout,分别用来装载两个Fragment。

平板版布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >        <!-- 装载列表的Fragment 的容器 -->    <LinearLayout         android:id="@+id/list_container"        android:orientation="vertical"        android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="2">    </LinearLayout>            <!-- 装载详情的Fragment 的容器 -->    <LinearLayout         android:id="@+id/detail_container"        android:orientation="vertical"        android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1">    </LinearLayout></LinearLayout>

        可能有人觉得这里乍一看,两个布局没什么区别啊。但是,请不要乍一看就下结论,这里其实是有区别的,而且是比较大的区别,看根标签就能看出来,手机版的是一个FrameLayout,而平板版的布局是一个LinearLayout。而且平板布局是有分权重的。这就是列表和详情页所占屏幕比例不同的原因。


       好了有了布局之后就可以写Activity部分的内容了。接下来看Activity的代码。

package com.example.fragmentdemo;import com.example.fragmentdemo3.R;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;public class MainActivity extends FragmentActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//建立一个左侧列表的FragmentFragment listFragment = new FragmentLeft();//得到一个管理器,用来管理FragmentFragmentManager fragmentManager = getSupportFragmentManager();//用FragmentManager打开一个Fragment事务FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//把刚建立的列表放到列表容器里fragmentTransaction.add(R.id.list_container, listFragment);//记得提交fragmentTransaction.commit();}}


       Activity里的代码十分简单,不过需要注意的是这里继承的不是普通的Activity,而是一个FragmetActivity,接下来和普通的Activity一样,我们需要为Activity设置布局文件,设置完成布局文件之后就是,管理在这个Activity上的Fragment了。先新建一个Fragment,然后得到一个Fragment的管理器。得到管理器之后还需要开启一个Fragment的事务,听起来似乎有些麻烦,但实际上代码就那么几行。

      最后用add方法把刚才建立的列表Fragment装到列表容器里,也就是布局文件里的Layout里。提交事务就即可。

      只有一个Fragment是看不出效果的,需要建立两个才行,否则屏幕是一个,Fragment也是一个,无法判断手机屏幕是否跳转,平板屏幕是否分屏。

      所以,接下来,建立两个Fragment,大家都知道,Fragment也是有自己布局的,实际上Fragment和一个小型的Fragment差不多,Fragment也有自己的生命周期。

刚才Activity里用到了列表页的Fragment,我们先看列表页的Fragment。

package com.example.fragmentdemo;import java.util.ArrayList;import java.util.List;import com.example.fragmentdemo3.R;import android.content.res.Configuration;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentManager.OnBackStackChangedListener;import android.support.v4.app.FragmentTransaction;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;/** *  * @author yufc * */public class FragmentLeft extends Fragment {private List<String> leftList = new ArrayList<String>();@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_left_layout, container, false);}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);//左侧ListViewfor(int i=0, count=20; i<count; i++){leftList.add("这是第" + i+"条数据");}//取到ListViewListView listView = (ListView) getActivity().findViewById(R.id.fragment_list);listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, leftList));listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {//得到一个新的Fragment,作为右侧的FragmentFragment rightFragment = new FragmentRight();//传递显示数据Bundle mBundle = new Bundle();mBundle.putString("arg", leftList.get(position));rightFragment.setArguments(mBundle);//建立一个Fragment的管理器final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();//判断横竖屏Configuration configuration = getActivity().getResources().getConfiguration();int ori = configuration.orientation;fragmentTransaction.replace(R.id.detail_container, rightFragment);//这里是为了让Fragment可以回退,不至于直接退出Activityif(ori == configuration.ORIENTATION_PORTRAIT){fragmentTransaction.addToBackStack(null);}fragmentTransaction.commit();}});}/** *  * @param msg */private void showTost(String msg){Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();}}


当然少不了为这个Fragment写一个布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#ff00ff99"    android:orientation="vertical" >    <ListView        android:id="@+id/fragment_list"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:cacheColorHint="@android:color/transparent"        android:fadingEdge="none" >    </ListView></LinearLayout>
布局很简单,LinearLayout里有一个ListView。


    这里Java代码有点长,但并不难理解。既然要建立一个Fragment,与要建立一个Activity的思路是相似的,建立Activity需要继承Activity类,同样建立一个Fragment需要继承Fragment类。之后需要复写Fragment的方法,这里复写的是onCreateView方法,在这个方法里需要对Fragment的布局初始化。方法就是用inflate方法。Fragment的生命周期是绑定在Activity上的,所以还需要复写一个OnActivityCreate方法,当Activity建立时进行一些必要的操作。
     在OnActivityCreate方法里,需要得到布局文件里的ListView,显示内容,设置一些数据也是必要的,这里只是用一个循环设置了一些数据,用一个最简单的Adapter来装载这些数据。接下来设置ListView的点击事件,点击完列表的条目之后自然是要显示详情,这里和Activity里相似,建立详情Fragment。这里不再赘述。


     相对来说详情Fragment就要简单多了。和列表相比简单到几乎没有什么内容,只是简单的得到列表页里传来的数据,显示出来而已。下面是详情Fragment的代码。

详情Fragment的Layout

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:background="#ff006600" >    <ListView        android:id="@+id/fragment_detail"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:cacheColorHint="@android:color/transparent"        android:fadingEdge="none" >    </ListView></LinearLayout>

也是LinearLayout下有一个ListView。

然后是Java代码

package com.example.fragmentdemo;import java.util.ArrayList;import java.util.List;import com.example.fragmentdemo3.R;import android.content.res.Configuration;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.LinearLayout;import android.widget.ListView;/** *  * @author yufc * */public class FragmentRight extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_right_layout, container, false);}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);//取出前一个Fragment传来的数据Bundle bundle = getArguments();String data = bundle.getString("arg");List<String> list = new ArrayList<String>();for(int i=0, count=20; i<count; i++){list.add(data);}LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.detail_container);ListView listView = (ListView) getActivity().findViewById(R.id.fragment_detail);listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list));}}


好了,大致就是这个样子了。

下面是Manifest文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.fragmentdemo3"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="16" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.fragmentdemo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

点击下载代码

0 0