Fragment是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间。

碎片的简单用法:
新建一个FragmentTest项目,然后新建一个左侧碎片布局left_fragment.xml,代码如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/button" />

</LinearLayout>

上面的代码功能是新建一个布局,只放置一个按钮,并让它水平居中显示。

然后新建一个右侧布局right_fragment.xml文件,代码如下:

<LinearLayout 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:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="@string/text_view" />

</LinearLayout>

上面的代码的功能是新建一个布局文件,背景为绿色,并放置了一个TextView用于显示一段文本。

接着新建一个LeftFragment类,继承自Fragment。LeftFragment类的代码如下所示:

package com.mfeng.fragmenttest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LeftFragment extends Fragment {
    @Override
    /**
     * 重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
     * inflate()方法将定义好的left_fragment布局动态加载进来。
     */
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }

}

上述的代码

重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
inflate()方法将定义好的left_fragment布局动态加载进来。

在新建一个RightFragment类,代码如下所示:

package com.mfeng.fragmenttest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class RightFragment extends Fragment {

    @Override
    /**
     * 重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
     * inflate()方法将定义好的right_fragment布局动态加载进来。
     */
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.right_fragment, container, false);

        return view;
    }

}

重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
inflate()方法将定义好的right_fragment布局动态加载进来。

修改activity_main.xml中的代码,如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >

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

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

</LinearLayout>

上述的代码中,使用<fragment>标签在布局中添加碎片,其中通过android:name属性来显式指明要添加的碎片类名。

注意:也要将类的包名加上。

运行程序,可以得到下面的图片:

动态的添加碎片

碎片的强大之处在于,它可以在程序运行时动态地添加到活动当中。

新建一个another_right_fragment.xml文件,代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff00"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/another_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/another_text_view" />

</LinearLayout>

上述的代码中新建一个背景为黄色的布局,设置一个文本框来显示文字。然后新建一个AnotherRightFragment类,代码如下:

package com.mfeng.fragmenttest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class AnotherRightFragment extends Fragment {

    /**
     * /**
     * 重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
     * inflate()方法将定义好的another_right_fragment布局动态加载进来。
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.another_right_fragment, container, false);

        return view;
    }

}

上述的代码

重写Fragment的onCreateView()方法,然后在这个方法中通过LayoutInflater的
inflate()方法将定义好的another_right_fragment布局动态加载进来。

修改activity_main.xml文件,代码如下所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false" >

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

    <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.mfeng.fragmenttest.RightFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    </FrameLayout>

</LinearLayout>

上述的代码中,将右侧布局放入FrameLayout中。

修改MainActivity中的代码,如下所示:

package com.mfeng.fragmenttest;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        //为Button按钮设置监听器
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {//创建待添加的碎片实例
                    AnotherRightFragment fragment = new AnotherRightFragment();
                    //获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到
                    FragmentManager fragmentManager = getFragmentManager();
                    //开启一个事务,通过调用beginTransaction()方法开启
                    FragmentTransaction transaction = fragmentManager.beginTransaction();
                    //向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例
                    transaction.replace(R.id.right_layout, fragment);
                    //提交事务,调用commit()方法来完成
                    transaction.commit();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

通过上面的代码,可以看出动态添加碎片主要分为5步:
1.创建待添加的碎片实例

AnotherRightFragment fragment = new AnotherRightFragment();

2.获取到FragmentManager,在活动中可以直接调用getFragmentManager()方法得到

FragmentManager fragmentManager = getFragmentManager();

3.开启一个事务,通过调用beginTransaction()方法开启

FragmentTransaction transaction = fragmentManager.beginTransaction();

4.向容器内加入碎片,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例

transaction.replace(R.id.right_layout, fragment);

5.提交事务,调用commit()方法来完成

transaction.commit();

Android学习笔记(十二)的更多相关文章

  1. 【转】 Pro Android学习笔记(二二):用户界面和控制(10):自定义Adapter

    目录(?)[-] 设计Adapter的布局 代码部分 Activity的代码 MyAdapter的代码数据源和构造函数 MyAdapter的代码实现自定义的adapter MyAdapter的代码继续 ...

  2. python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL

    python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(a ...

  3. Go语言学习笔记十二: 范围(Range)

    Go语言学习笔记十二: 范围(Range) rang这个关键字主要用来遍历数组,切片,通道或Map.在数组和切片中返回索引值,在Map中返回key. 这个特别像python的方式.不过写法上比较怪异使 ...

  4. 【转】Pro Android学习笔记(二):开发环境:基础概念、连接真实设备、生命周期

    在Android学习笔记(二):安装环境中已经有相应的内容.看看何为新.这是在source网站上的Android架构图,和标准图没有区别,只是这张图颜色好看多了,录之.本笔记主要讲述Android开发 ...

  5. 【转】 Pro Android学习笔记(二十):用户界面和控制(8):GridView和Spinner

    目录(?)[-] GridView Spinner GridView GridView是网格状布局,如图所示.在了解ListView后,很容易了解GridView.下面是例子的XML文件. <? ...

  6. 【转】Pro Android学习笔记(二五):用户界面和控制(13):LinearLayout和TableLayout

    目录(?)[-] 布局Layout 线性布局LinearLayout 表格布局TableLayout 布局Layout Layout是容器,用于对所包含的view进行布局.layout是view的子类 ...

  7. 【转】 Pro Android学习笔记(二九):用户界面和控制(17):include和merge

    目录(?)[-] xml控件代码重用include xml控件代码重用merge 横屏和竖屏landsacpe portrait xml控件代码重用:include 如果我们定义一个控件,需要在不同的 ...

  8. Android学习笔记(二十二)——短信接收与发送

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 当手机接收到一条短信的时候, 系统会发出一条值为 android.provider.Telephony.SMS ...

  9. Android学习笔记(二十)——自定义内容提供器

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 如果我们想要实现跨程序共享数据的功能,官方推荐的方式就是使用内容提供器,可以通过新建一个类去继承 Conten ...

  10. Android学习笔记(二十一)——实战:程序数据共享

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 我们继续在Database项目的基础上继续开发,通过内容提供器来给它加入外部访问接口.首先将 MyDataba ...

随机推荐

  1. SqlServer 数据库 引擎优化使用(六)

    一:新建模板 二:选择跟踪的语句类型: 使用模板: 把范文的行为进行记录: 开启引擎: 选择文件和数据库: 选择选项: 分析的结果:

  2. 19、lambda表达式树

    一.定义: 表达式树又称为表达式目录树,以数据形式表示语言级代码.所有的数据都存储在树结构中,每个结点表示一个表达式(Expression). 二.要点: –Lambda表达式的参数类型可以忽略,因为 ...

  3. JAVA并发框架之Semaphore实现生产者与消费者模型

    分类: Java技术      锁和信号量(Semaphore)是实现多线程同步的两种常用的手段.信号量需要初始化一个许可值,许可值可以大于0,也可以小于0,也可以等于0.      如果大于0,表示 ...

  4. MVC+UnitOfWork+Repository+EF 之我见

    UnitOfWork+Repository模式简介: 每次提交数据库都会打开一个连接,造成结果是:多个连接无法共用一个数据库级别的事务,也就无法保证数据的原子性.一致性.解决办法是:在Reposito ...

  5. 十分钟了解分布式计算:GraphX

    GraphX原型论文 GraphX是Spark中用于图(e.g., Web-Graphs and Social Networks)和图并行计算(e.g., PageRank and Collabora ...

  6. JUCE 界面库显示中文乱码问题

    JUCE 界面库显示中文乱码问题 环境: Windows7 64位 旗舰版 Visual Studio Ultimate 2012 JUCE 4.1 问题描述: 直接使用juce::String存储中 ...

  7. Bitmap文件格式+生成一个BMP文件

    Bitmap的文件格式: #define UINT16 unsigned short #define DWORD unsigned int #define WORD short #define LON ...

  8. Chp11 11.7

    <Java语言程序设计>P327 题目要求使用数组来模拟实现ArrayList的一些方法,并要求可以根据实际长度来实现数组自动增长,这里只贴出LikeArrayList.java 测试方法 ...

  9. Android之QQ登录界面

    首先过程中碰到的几个问题: 1.对 EditText 进行自定义背景 2.运行时自动 EditText 自动获得焦点 3.在获得焦点时即清空 hint ,而不是输入后清空 4.清空按钮的出现时机(在得 ...

  10. it小小鸟

    It小小鸟观后感 每个人的理想目标都是不同的,很多人有自己的理想.却被困于现实而止步不前.一篇<it小小鸟>让我却懂得,一个人如果想有所作为,就不能止步不前.光有一个远大的理想是然并卵的. ...