前情提要(Previously)

本系列将使用 Android Studio 将《第一行代码》(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Android Studio 作为开发 IDE 的同学开路。

PS:其实我就是现学现卖,希望我能坚持刷完。

在前面已经学习了 Android 四大组件中的 Activity,这次来学习一下Activity 中的 Fragment。

系列目录在此:

摘要(Abstract)

Fragment 的简介、简单使用、动态加载。

Fragment 是什么

先来看看 API Guides 里是怎么说的。

*

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle.

*

  • Fragment 必须嵌入在 Activity 中使用。
  • Fragment 的生命周期 是受 Activity 影响的。
  • 可以在一个 Activity 中使用多个 Fragment。
  • Fragment 可以在多个 Activity 中重用。

说了这么多,也没说 Fragment 到底是什么,只好继续往下看。

Design Philosophy(设计理念)

Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.

  • Android3.0 里出现的。
  • 为了更加合理和充分地利用大屏幕的空间。

其实就是为了更好的同时支持手机和平板(我是这么认为的)。看下面这个来自 Android API Guides 中的图就明白了。

Fragment 简单使用

练习开始,新建一个 FragmentTest 的项目,在一个 Activity 中添加两个 Fragment,并列显示。

  • 新建一个左侧布局 left_fragment.xml,放一个 Button 在里面,代码如下:
  <Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button" />
  • 同样的新建一个右侧布局 right_fragment.xml,放一个 TextView 在里面,代码省略。

  • 新建 LeftFragment 类,继承自 Fragment,重写 onCreateView() 方法,在这个方法中通过 LayoutInflater 将布局动态加载进来,代码如下:

public class LeftFragment extends Fragment {

@Override

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

View view = inflater.inflate(R.layout.left_fragment,container,false);

return view;

}

}

  • 同样新建 RightFragment 类,代码省略。

  • 修改 activity_main.xml,删掉默认的 TextView 添加 Fragment,代码如下:

<fragment
android:id="@+id/left_fragment"
android:name="com.addict.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></fragment> <fragment
android:id="@+id/right_fragment"
android:name="com.addict.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></fragment>

这样最简单的 Fragment 示例就写好了,运行一下程序看看吧。

动态添加 Fragment

  • 新建一个 another_right_fragment.xml,放一个 TextView 在里面,设定布局的颜色、TextView 的内容,代码如下:
  <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="this is another right fragment."
android:textSize="20sp" />
  • 同样新建一个 AnotherRightFragment 类,代码省略。

  • 修改 activity_main.xml 的代码,将右侧的 Fragment 放在 FrameLayout 中,代码如下:

<fragment
android:id="@+id/left_fragment"
android:name="com.addict.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></fragment> <FrameLayout
android:id="@+id/right_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"> <fragment
android:id="@+id/right_fragment"
android:name="com.addict.fragmenttest.RightFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"></fragment>
</FrameLayout>
  • 修改 MainActivity 中的代码,在点击 Button 是动态添加 Fragment,代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AnotherRightFragment fragment = new AnotherRightFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout, fragment);
transaction.commit();
}
});
}

这样就完成了,运行一下看看吧。小结一下动态添加 Fragment:

  1. 创建待添加的 Fragment 的实例。
  2. 获取 FragmentManager,通过 getFragmentManager() 方法。
  3. 开启事务。
  4. 向容器内加入 Fragment,使用 replace() 方法,参数为需要传入的容器 id、待添加的 Fragment 实例。
  5. 提交事务。

利用返回栈管理 Fragment

运行之前的程序,点击 Button 动态添加 Fragment 后,按下 Back 键我们发现程序直接退出了。那么能不能做到按 Back 键回到上一个 Fragment 呢?

超简单,在这句代码 transaction.commit(); 前再加一句代码 transaction.addToBackStack(null); 就可以了,试试看吧。

2015-03-21 更正

按照上面写的加上这句代码 transaction.addToBackStack(null); 之后,我发现按下 Back 仍然没有返回上一个 Fragment,还是直接退出程序了。Google Baidu 查了好久也没弄明白原因。

写了个解决办法,在 MainActivity 中重写了 onPressed() 方法,代码如下:

@Override
// 按下 Back 按钮时触发
public void onBackPressed(){
FragmentManager fragmentManager = getFragmentManager();
// 判断 BackStack 中是否有 FragmentTransaction
if(fragmentManager.getBackStackEntryCount() > 0){
// FragmentTransaction 出栈,恢复前一个 Fragment
fragmentManager.popBackStack();
return;
}
super.onBackPressed();
}

其它(Miscellaneous)

尽管我试图在本文中尽量完整的进行描述,但受限于篇幅和我的个人水平,本文难免有所遗漏,欢迎在评论中指出。

如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!

关于作者(About Me)

addict

原文链接:http://www.cnblogs.com/DebugLife/p/4355669.html

本文谢绝转载,如需转载需征得作者本人同意,谢谢。

Android Studio 单刷《第一行代码》系列 05 —— Fragment 基础的更多相关文章

  1. Android Studio 单刷《第一行代码》系列目录

    前言(Prologue) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Android ...

  2. Android Studio 单刷《第一行代码》系列 06 —— Fragment 生命周期

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  3. Android Studio 单刷《第一行代码》系列 02 —— 日志工具 LogCat

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  4. Android Studio 单刷《第一行代码》系列 01 —— 第一战 HelloWorld

    前言(Prologue) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Android ...

  5. Android Studio 单刷《第一行代码》系列 07 —— Broadcast 广播

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  6. Android Studio 单刷《第一行代码》系列 04 —— Activity 相关

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  7. Android Studio 单刷《第一行代码》系列 03 —— Activity 基础

    前情提要(Previously) 本系列将使用 Android Studio 将<第一行代码>(书中讲解案例使用Eclipse)刷一遍,旨在为想入坑 Android 开发,并选择 Andr ...

  8. 【java学习系列】 Android第一本书《第一行代码》

    开始Java的学习,从Android,开始吧.<第一代码>开始阅读和调试demo例子. 下面是 <第一行代码>的思维导图:

  9. Android Studio:Unable to add window android.view.ViewRootImpl$W@5e2d85a -- permission denied for this window 第一行代码

    学习<第一行代码>的时候,出现的错误. java.lang.RuntimeException: Unable to start receiver com.example.sevenun.l ...

随机推荐

  1. poj 1201 差分约束

    http://www.cnblogs.com/wangfang20/p/3196858.html 题意: 求集合Z中至少要包含多少个元素才能是每个区间[ai,bi]中的元素与Z中的元素重合个数为ci. ...

  2. IOS下视频监控项目总结

    一.项目说明 二.技术点 1.数据缓存 2.storyboard的使用 3.h264码流数据的解码 4.UDP通讯 三.解决方案 四.总结 五.相关资料

  3. sqlserver2005数据库18456错误(转)

    第一步.以windows验证模式进入数据库管理器.第二步:右击sa,选择属性:在常规选项卡中,重新填写密码和确认密码(改成个好记的).把强制实施密码策略去掉.第三步:点击状态选项卡:勾选授予和启用.然 ...

  4. 第一次知道Winform的窗体之间传值怎么写,分享给小白~

    之前为了这事,百度了一天也没找到,最终使用了静态变量了. 窗体Form1: private void button1_Click(object sender, EventArgs e) { var f ...

  5. Annotation注解与butterknife

    注解分为三种,一般来讲我们使用的是运行时会加载及能够反射读取的注解类型, 其他编译器生效的类型和编译后放入类文件而运行期不能加载解析的对我们没啥用. 所以从普通理解上来看,注解要配合着反射用就好了. ...

  6. 【Cocos2d入门教程一】Cocos2d-x环境搭建

    在进行Cocos2d游戏开发前 我们先来配置一下环境,我们先来准备一下工具,我们所需要的工具分别为: 1.Cocos2d引擎 2.JDK 3.SDK 4.NDK 5.ANT 6.ADT 1.下载Coc ...

  7. 深入理解JavaScript中的this关键字

    1. 一般用处 2. this.x 与 apply().call() 3. 无意义(诡异)的this用处 4. 事件监听函数中的this 5. 总结 在JavaScript中this变量是一个令人难以 ...

  8. 编辑器笔记——sublime text3 编译sass

    如已经安装sass 和 sass build两个插件到ST,command+b编译也没有问题,那么另外安装koala,在koala中引入你要编辑的sass,并把该sass文件设置为自动编译,那么用ST ...

  9. PHP标签的格式

    PHP标签的格式: 1.xml格式(推荐的,标准的标记) <?php    php代码?> 示例: 2.短格式 <? php代码 ?> 此种格式需要在php.ini中配置 示例 ...

  10. 一些值得思考的"小题"一

    如下是我们查找数组中某个元素的一种通常做法 const int *Find(const int *array, int length, int x) { const int *p = array; ; ...