Fragment基础操作

Fragment和Activity类似,同样是具备UI的属性;也就是都能用于规划UI布局...

Building a Dynamic UI with Fragments --> Fragments具备有动态UI的属性。为了在Android上为用户提供动态的、多窗口的交互体验,我们需要将UI组件和Activity操作封装成模块进行使用,使得我们可以在activity中对这些模块进行切入切出操作。可以用Fragment来创建这些模块,Fragment就像一个嵌套的activity,拥有自己的布局(layout)并管理自己的生命周期。

主题一:创建Fragment

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).

可能使用到的 Android API:Note: If you decide that the minimum API level your app requires is 11 or higher, you don‘t need to use the Support Library and can instead use the framework‘s built in Fragment class and related APIs. Just be aware that this lesson is focused on using the APIs from the Support Library, which use a specific package signature and sometimes slightly different API names than the versions included in the platform. 支持包中的Fragment类及相关API和Android系统内置的Fragment和API有不同。若使用Android API 11以上的系统,则不需要使用支持包。

Fragment和Activity类似,都具有自己的生命周期callbacks,以及相关的逻辑;创建Fragment实例时,首先要做的是继承Fragment类,必须覆写onCreateView(),已确定其Layout(具体的UI外表);同时该方法也是唯一需要覆写以便让Fragment运行。

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class ArticleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);
    }
}

Just like an activity, a fragment should implement other lifecycle callbacks that allow you to manage its state as it is added or removed from the activity and as the activity transitions between its lifecycle states. Fragment从Activity中添加或移除都能够获取到系统消息,同时执行相关的Fragment系统回调方法。

比如:如果Activity执行了onPause()回调,在Activity中的Fragment会收到消息以执行onPause()。

使用.xml文件为Activity添加Fragment实例

Fragments是可重用的、模块化的UI组件,每个Fragment的实例都必须与一个FragmentActivity关联。我们可以在Activity的XML布局文件中定义每一个fragment来实现这种关联。

Note: FragmentActivity is a special activity provided in the Support Library to handle fragments on system versions older than API level 11. If the lowest system version you support is API level 11 or higher, then you can use a regular Activity. 此处的LinearLayout相当于是一个容器,用于容纳Fragment。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <fragment android:name="com.example.android.fragments.HeadlinesFragment"
              android:id="@+id/headlines_fragment"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="match_parent" />
    <fragment android:name="com.example.android.fragments.ArticleFragment"
              android:id="@+id/article_fragment"
              android:layout_weight="2"
              android:layout_width="0dp"
              android:layout_height="match_parent" />
</LinearLayout>

上述是一个.xml文件实例,在Activity的.xml文件中添加了两个Fragment。并通过以下手法将该.xml文件布局到Activity中:

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);
    }
}

P.S. 上述MainActivity继承了FragmentActivity。Note: When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot remove the fragment at runtime.使用静态方式(在.xml文件中定义了Fragment)添加了Fragment,不能实现动态添加和移除。

主题二:创建灵活的UI组件---Fragment

Fragment的一个可能的使用场景:When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space.

The FragmentManager class provides methods that allow you to add, remove, and replace fragments to an activity at runtime in order to create a dynamic experience.

运行状态下添加Fragment

这种方式不同于之前的使用.xml文件方式添加Fragment,而是可以在运行时动态进行添加和移除Fragment。This is necessary if you plan to change fragments during the life of the activity.

To perform a transaction such as add or remove a fragment, you must use the FragmentManager to create a FragmentTransaction, which provides APIs to add, remove, replace, and perform other fragment transactions.

If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity‘s onCreate() method. 如果需要在允许其移除或更换Fragment,必须要在Activity的onCreate()回调中初始化该Fragment。

An important rule when dealing with fragments—especially when adding fragments at runtime—is that your activity layout must include a container View in which you can insert the fragment. 另外一个需要注意的地方:Activity必须包含一个能够容纳Fragment的容器。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

上述就是一个“空”容器---the fragment container

Inside your activity, call getSupportFragmentManager() to get a FragmentManager using the Support Library APIs. Then call beginTransaction() to create a FragmentTransaction and call add() to add a fragment.

You can perform multiple fragment transaction for the activity using the same FragmentTransaction. When you‘re ready to make the changes, you must call commit().

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);
        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {
            // However, if we‘re being restored from a previous state,
            // then we don‘t need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            // Create a new Fragment to be placed in the activity layout
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent‘s extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the ‘fragment_container‘ FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}

将Fragment实例添加到R.id.fragment_container为标识的容器中。

运行状态下替换Fragment

The procedure to replace a fragment is similar to adding one, but requires the replace() method instead of add(). 使用的是replace()而不是add()。

Keep in mind that when you perform fragment transactions, such as replace or remove one, it‘s often appropriate to allow the user to navigate backward and "undo" the change. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction. 为了编译较好的用户体验,需要提供“Undo”按键,方便退回到先前状态。可使用addToBackStack()方法让Fragment入栈,以便退回到先前状态。

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced. 添加到BackStack的区别。

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();

主题三:Fragment之间的交互

为了重用Fragment UI组件,我们应该把每一个fragment都构建成完全的自包含的、模块化的组件,定义他们自己的布局与行为。定义好这些模块化的Fragment后,就可以让他们关联activity,使他们与application的逻辑结合起来,实现全局的复合的UI。

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly. Fragment之间的交互是通过其“宿主”---Activity,而不能直接进行交互。

为了让Fragment和Activity交互,可以在Fragment中定义一个Interface。

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;
    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    ...
}

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface. Fragment --> Activity 信息流走向

或者是通过点击事件,将该事件传递到Activity中:

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Send the event to the host activity
        mCallback.onArticleSelected(position);
    }

并让Activity实现该接口:OnHeadlineSelectedListener,并处理相关接口中的方法

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
    }
}

如何让信息从 Activity --> Fragment 中

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment‘s public methods. 也就是在Activity中获取到Fragment实例,直接调用其方法即可。

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...
    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);
        if (articleFrag != null) {
            // If article frag is available, we‘re in two-pane layout...
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we‘re in the one-pane layout and must swap frags...
            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);
            // Commit the transaction
            transaction.commit();
        }
    }
}
时间: 2024-10-11 06:37:03

Fragment基础操作的相关文章

vsphere基础操作-网络

一.vsphere网络操作 概念: portgroup:通信端口组.在vsphere中,一共包含三种端口组. 1)管理网络:management network,可以理解为EXSI主机的管理IP地址.每个EXSI必须配置一个管理网络IP,使得vc能够管理到exsi.每个EXSI只能有一个唯一的管理网络. 2)内核:vmkernel,可以理解为EXSI的后端IP,使得后端各项功能能够实现.这里所说的后端功能指的是EXSI之间的通讯以实现VMOTION等高级功能.连入ISCSI或NAS等存储.FT功

Mysql安装和基础操作

1.环境检查: 先检查是否已经安装了:rpm -qa |grep mysql ---两个都检查下,查看mysql是否安装 rpm -qa |grep MySQL若安装有可删除:rpm -e ****** 2.安装:1)安装前准备:mkdir usr/mysql cd进入该目录,上传安装包到/usr/mysql目录下2)安装:rpm -ivh MySQL-server-5.0.16-0.i386.rpm rpm -ivh MySQL-elient-5.0.16-0.i386.rpm3)验证安装是否

双向链表的基础操作(C++实现)

★C++实现双向链表的基础操作(类的实现) #include<iostream> #include<cassert> using namespace std; typedef int DataType; class double_link_list {                        //定义双向链表类,包括了双向的前驱和后继指针,以及对象的初始化 public: friend class ListNode; double_link_list(DataType x =

数据结构-线性表的一些基础操作 c++代码

//线性表的顺序存储结构 template <class T> class Linearlist { public: Linearlist(int MaxListSize == 10); ~Linearlist() { delete []element; } bool IsEmpty() const { return length == 0; } bool IsFull() const { return length == MaxSize; } int Length() const { ret

php之文件基础操作

在php中对文件的基础操作非常的简单,php提供的函数粗略的用了一遍. file_get_contents():可以获取文件的内容获取一个网络资源的内容,这是php给我封装的一个比较快捷的读取文件的内容.网络资源的函数,此函数里面封装了对文件的打开,读取,关闭操作.一次性的将内容全部读取到内存中,相当方便,但是对于大文件或者网络资源较大的时候,不建议使用.file_put_contents():写入数据,和file_get_contents()类似. 文件的基础操作:touch()--新建,fo

环境变量,属性文件,文件基础操作,目录基础操作,遍历指定后缀名文件

环境变量和属性 环境变量相关: 1.得到某个/所有环境变量的值 2.设置环境变量的值 3.列出全部系统属性名 import java.util.Enumeration; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; public class Environment { public static void main(String[] args) { // TODO Auto-gener

SQLSERVER 数据库基础操作

1.修改表中字段的长度,类型为varchar,从30改到50 语句执行(注:当前为30): alter table 表名 alter column 列名 varchar(50) 2.增加字段: alter table 表名 add 字段 varchar(50) SQLSERVER 数据库基础操作,布布扣,bubuko.com

mysql的基础操作指令整理|环境redhat6

1.安装 yum-y install mysql mysql-server service mysqld start|stop|restart        ##启动|停止|重启 chkconfig mysqld on|off                  ##开机启动|关闭 此时输入:mysql就能启动进入(记得是start状态) 2.改密 mysqladmin –uroot password             ##创建密码 mysqladmin–uroot –pxxoo passw

Mac下Git的基础操作

目前最火的版本控制软件是Git了吧,今天简单梳理一下Mac下Git的基础操作~~ 一.什么是Git Git是一个分布式代码管理工具,用于敏捷的处理或大或小的项目,类似的工具还有svn. 基于Git的快速的.免费的.稳定的在线代码托管平台有github,还有一些国内的,coding.csdn代码托管平台.京东代码托管平台等等. 二.Git的基本使用 1.注册一个git账号 咱们以coding代码托管平台为例来简单介绍 A.登陆coding网站https://coding.net/,注册coding