Fagment 与 Fragment之间通信(交互)

Fagment 与 Fragment之间通信建立在Fragment与Activity交互,Activity作为桥梁来沟通fragment之间的通信;

一、首先Fragment必须含有自定义的接口参数,如下:

public class ArticleFragment extends Fragment{
    private ImageView iv;
    //自定义的接口
    ArticleFragmentListener mCallback;
    private int key=1;
    private int[] images={R.drawable.img01,R.drawable.img02,R.drawable.img03};

    public interface ArticleFragmentListener{
        public void onArticleSelected(int index);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
    }

    private void initUI(View view) {
        iv=(ImageView) view.findViewById(R.id.iv);
        Bitmap bitmap=ResToBitmap.getBitmap(getActivity(), images[0]);
        iv.setImageBitmap(bitmap);
        iv.setOnClickListener(getOnClickLis());
    }

    private OnClickListener getOnClickLis() {
        OnClickListener lis=new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mCallback.onArticleSelected((key++)%3);
            }
        };
        return lis;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_item, container, false);
        initUI(view);
        return view;
    }

    //在onAttach中捕获接口的实现(在Activity中实现该接口),然后调用接口的方法与Activity交互
    @Override
    public void onAttach(Activity activity) {
        try{
            mCallback=(ArticleFragmentListener) activity;
        }catch(ClassCastException e){
            throw new ClassCastException(activity.toString()+"必须实现 ArticleFragmentListener");
        }

        super.onAttach(activity);
    }

}

二、在Activity中实现该Fragmeng的接口实例,在实现的方法中通过getFragmentManager().findFragmentById(R.id.fragment_id2)获取别的fragment更新该Fragment的试图:

public class MainActivity extends FragmentActivity implements ArticleFragment.ArticleFragmentListener{

    private FragmentManager fragManager;
    private FragmentTransaction fragTra;
    private ArticleFragment articleFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
        setPreference();
        articleFragment=new ArticleFragment();
        fragManager=getFragmentManager();
        fragTra=fragManager.beginTransaction();
        //fragment切换样式
        fragTra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragTra.add(R.id.fragment_id, articleFragment);
        fragTra.commit();
    }
    /**
     * 将图片(int)保存到Prefrence中
     */
    private void setPreference() {
        SharedPreferences sp=this.getSharedPreferences(getString(R.string.mainctivitySp),this.MODE_WORLD_READABLE);
        Editor editor=sp.edit();
        editor.putInt("img01", R.drawable.img01);
        editor.putInt("img02", R.drawable.img02);
        editor.putInt("img03", R.drawable.img03);
        editor.commit();
    }
    private void initUI() {
    }

//实现fragment的借口实例并向另外的Fragment传递数据更新视图
    @Override
    public void onArticleSelected(int index) {
//      Toast.makeText(this, "fagment传递过来的数据:"+index, Toast.LENGTH_LONG).show();
        ArticleFragment2 article=(ArticleFragment2) getFragmentManager().findFragmentById(R.id.fragment_id2);
        if(article!=null){
            article.updateView(index);//调用该Fragment的更新视图方法
        }
    }
}

对应的xml布局:

<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidtrainingforfragment.MainActivity" >

    <FrameLayout 
        android:id="@+id/fragment_id"
        android:layout_width="fill_parent"
        android:layout_height="200dp"

        />

    <fragment
        android:id="@+id/fragment_id2"
        android:name="com.example.androidtrainingforfragment.fragment.ArticleFragment2"
         android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/fragment_id" />

</RelativeLayout>

三、需要更新试图的Fragment

public class ArticleFragment2 extends Fragment{
    private ImageView iv;
    private int key=1;
//  private int[] images={R.drawable.img01,R.drawable.img02,R.drawable.img03};
    private int[] images=new int[3];
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        SharedPreferences sp=getActivity().getSharedPreferences(getString(R.string.mainctivitySp),getActivity().MODE_WORLD_READABLE);
        images[0]=sp.getInt("img01", 0);
        images[1]=sp.getInt("img02", 0);
        images[2]=sp.getInt("img03", 0);
//      Log.i("images[0]",">>>>>"+images[0]);

    }

    private void initUI(View view) {
        iv=(ImageView) view.findViewById(R.id.iv);
        Bitmap bitmap=ResToBitmap.getBitmap(getActivity(), images[0]);
        iv.setImageBitmap(bitmap);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_item, container, false);
        initUI(view);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        /*
        try{
            mCallback=(ArticleFragmentListener) activity;
        }catch(ClassCastException e){
            throw new ClassCastException(activity.toString()+"必须实现 ArticleFragmentListener");
        }
        */
        super.onAttach(activity);
    }
    public void updateView(int position){
        Bitmap bitmap=ResToBitmap.getBitmap(getActivity(), images[position]);
        iv.setImageBitmap(bitmap);
    }
}

总结:从上面可以看出两个Fragment要进行通信必须由Activity作为桥梁,需要完成Fragment向Activity的通信,Activity向Fragment的通信;其中在前面一种通信中onAttach()方法捕捉到接口的实现,从而将Fagment数据传递给Activity,后一种主要是在Activity中利用getFragmentManager().findFragmentById()获取对应的Fragment,调用该Fragment相应的方法更新视图等的操作;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值