码迷,mamicode.com
首页 > 其他好文 > 详细

fragment及fragment的通信

时间:2016-05-07 09:01:21      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

引用API的一段话作为开头A Fragment is a piece of an application‘s user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().
大概意思就是说Fragment是Activity中的一个片段,这些片段组成了一个activity。他们之间需要通过FragmentManager进行通信。
所以对于fragment来说,它是有生命周期的,生命周期对fragment的应用很重要。生命周期如下技术分享
下面是官方文档的介绍

onAttach(Activity) called once the fragment is associated with its activity.
onCreate(Bundle) called to do initial creation of the fragment.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
onStart() makes the fragment visible to the user (based on its containing activity being started).
onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:

onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
onDestroyView() allows the fragment to clean up resources associated with its View.
onDestroy() called to do final cleanup of the fragment‘s state.
onDetach() called immediately prior to the fragment no longer being associated with its activity.

其中应用得最为广泛后者经常使用的有:
onAttach(Activity):当该Fragment被添加到Activity时被回调。该方法只会被调用一次,这个方法经常用于fragment的通信,因为他回调了一个activity参数。
onCreateView(LayoutInflater, ViewGroup, Bundle):每次创建,绘制该fragment的view组件时回调该方法。这个应用于绘制fragment内的UI界面。
onActivityCreated(Bundle):当Fragment所在的Activity被启动完成后回调该方法。我们看上面的生命周期可以知道,这个方法是以个节点,由于他的特殊性,我们一般在这里面调用activity里面的findViewById(),不能是fragment内部的id,即getActivity().findViewById();
其他的方法就不一个个细说了。
生命周期说完了,我们在来看下fragment到底怎么用,我先画个思维导图
技术分享
先看静态添加,关键是必须在xml里面加入name属性指向自定义的fragment,tools属性只是为了能够预览,没有其他的作用

       <fragment
                android:id="@+id/top_frag"
                android:name="com.vincesheng.optionselect.fragment.TopFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:layout="@layout/add_button" />

根据上面所说我们先给TopFragment建立布局文件

<com.vincesheng.optionselect.view.FlowLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fl_frag"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</com.vincesheng.optionselect.view.FlowLayout >

然后在TopFragment这个类里面,这样就能显示出这个fragment了

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_top, container, false);
        mFl = (FlowLayout) v.findViewById(R.id.fl_frag);
        return v;
    }

我们再来看动态添加:
我在前几篇文章说过,必须用单例模式初始化

public static TopFragment newInstance(String title) {
        Bundle b = new Bundle();
        b.putString("TITLE", title);
        TopFragment fragment = new TopFragment();
        fragment.setArguments(b);
        return fragment;
    }

然后在调用下面几句话就可以动态添加了,当然在布局文件里你需要有这样一个容器:R.id.content_container ,add,remove方法就不在赘述

TopFragment topFragment = TopFragment.newInstance("");
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content_container ,topFragment);
        fragmentTransaction.commit();

在动态添加中还有一个点就是back栈,一个容器维护一个一个栈。所以add方法中,始终只有一个栈,没什么意义(这里只可意会不可言传,读者看了下面的replace看能不能理解这里)。我们研究replace方法中的栈,如下图的过程。
技术分享
实现代码如下

      TopFragment topFragment = TopFragment.newInstance("");
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content_container ,topFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

那么fragment是怎么进行通信的呢?其实有很多方法,我们这里只讲一种,接口通信,看代码
在TopFragment.java里面定义接口

public interface Callbacks{
        public void onDragToLoction(String resouceId);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (!(context instanceof Callbacks)) {
            throw new IllegalStateException("Activity必须实现Callback接口");
        }
        mCallbacks = (Callbacks) context;//因为父Activity实现了callBack接口所以可以强制类型转换
    }

在父activity里面实现接口

public class TestActivity extends Activity implements View.OnClickListener, TopFragment.Callbacks{
    private TopFragment TFrag;
    private BottomFragment BFrag;
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        FontIconTypefaceHolder.init(getAssets(), "fontawesome-webfont.ttf");
    }
    @Override
    public void onDragToLoction(String resourceId) {
        BFrag = (BottomFragment)getFragmentManager().findFragmentById(R.id.bottom_frag);
        BFrag.setTvText(resourceId);
    }
    }

然后在TopFragment里面去触发这个接口就行了。

mCallbacks.onDragToLoction(getResources().getString(R.string.fa_trash_o));

fragment及fragment的通信

标签:

原文地址:http://blog.csdn.net/u013260304/article/details/51330363

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!