2、Activity 与 Fragment 之间常见的几种通信方式

一、activity与activity之间的通信(该方式比较简单,就一笔带过)

1、通过intent将值传给即将跳转的activity

Intent intent = new Intent(getContext(), ACOne.class);
intent .putExtra("f", "diyige");
startActivity(inten);/*跳转到下一个页面*/

或者通过bundle

     //新建一个显式意图,第一个参数为当前Activity类对象,第二个参数为你要打开的Activity类
        Intent intent =new Intent(MainActivity.this,MainActivity2.class);
        //用Bundle携带数据
        Bundle bundle=new Bundle();
        //传递name参数为tinyphp
        bundle.putString("name", "tinyphp");
        intent.putExtras(bundle);
        startActivity(intent);

2、通过startActivityForResult的跳转方式将值传给跳转前的activity

   Intent intent=new Intent(this,NextActivity.class);
   startActivityForResult(intent,1);//1是requestCode,用于标识请求的来源,在下面的onActivityResult中的requestCode可以区分业务

在下面回调中获取传过来的值

    //当开启的activity关闭时调用,也就是下一个activity关闭时,在当前的activity调用  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //requestCode 是从下一个activity关闭的时候传过来的  
        if(resultCode==10) {
//data就是下一个页面的意图  
            String name = data.getStringExtra("name");
            tx.setText(name);
        }else if(resultCode==20){

        }
    }
}  

二、fragment与fragment之间的通信

在fragment1中通过getSupportFragmentManager().findFragmentByTag()获取fragment2的对象,调用fragment2中的方法将值传过去
Fragment1

package com.wangdong.myapplication;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class Fragment1 extends Fragment implements View.OnClickListener {
    private View myFragmentView;
    private View view;
    private Button mBtn;
    private TextView mTv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (myFragmentView == null) {
            myFragmentView = inflater.inflate(R.layout.fragment_fragment1, container, false);
        }
        initView();
        return myFragmentView;
    }

    private void initView() {
        mBtn = (Button) myFragmentView.findViewById(R.id.btn);
        mTv = (TextView) myFragmentView.findViewById(R.id.tv);
        mBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                ///"fragment2"是fragment2的tag,new的时候传入的
                Fragment2 f2 = (Fragment2) getActivity().getSupportFragmentManager().findFragmentByTag("fragment2");
                f2.setTextView("fragment传值给我了");
                break;
            default:
                break;
        }
    }
}

Activity中创建fragment,并给fragment指定tag

        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();
        //第三个参数为tag 
        fragmentTransaction.add(R.id.fragment1,fragment1,"fragment1");
        fragmentTransaction.add(R.id.fragment2,fragment2,"fragment2");
        fragmentTransaction.commit();

Fragment2

package com.wangdong.myapplication;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class Fragment2 extends Fragment {
    private View myFragmentView;
    private View view;
    private TextView mTv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (myFragmentView == null) {
            myFragmentView = inflater.inflate(R.layout.fragment_fragment2, container, false);
        }
        initView();
        return myFragmentView;
    }

    private void initView() {
        mTv = (TextView) myFragmentView.findViewById(R.id.tv);
    }

    public void setTextView(String str){
        if(mTv != null){
            mTv.setText(str);
        }
    }
}
gif.gif

三、activity传值给fragment

1、通过setArguments传递bundle,通过getArguments获取bundle
activity

 FragmentTransaction ft=fm.beginTransaction();
        OneFragment oneFragment=new OneFragment();
        ft.replace(R.id.frame,oneFragment,"f1");
        Bundle bundle=new Bundle();
        bundle.putString("one","要传的值");
        oneFragment.setArguments(bundle);
        ft.commit();
    Fragment中:
        Bundle bundle=getArguments();
        String s=bundle.getString("one");

2、通过fragment中的attach()生命周期,将context转为Mainactivity,然后调用MainActivity中的方法

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        str = ((MainActivity)context).toFragmentone();
        Log.e("ss",str);

    }

四、fragment传值给activity

通过在fragment中实现接口的方式,Fragment向Activity传值的步骤 接口回调传递(5部曲)
1.fragment中准备回调接口 接口中声明传值的回调方法
2.在fragment中定义属性private MyListener myListener
3.重写fragment中的onAttach()方法:listener = (MyLisener)getActivity();
4.fragment触发事件时回传值
5.Activity中实现回调接口 重写回调方法获取回传的值并显示

import android.content.Context;
public class FragmentOne extends Fragment {

    private Button btn;
    private TextView text;
    private String str;
    private MyListener ac;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragmentone,null);
        // 给fragment上的按钮添加点击事件
        text = v.findViewById(R.id.tv_fragmentone);
        btn = v.findViewById(R.id.getImgae);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //通过调用在activity中实现的接口方法,吧数据传给Mainactivity
       ac.sendContent("dddd");
    }
});
        return v;
    }

        //activity和fragment联系时候调用,fragment必须依赖activty
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //获取实现接口的activity
     ac = (MyListener) getActivity();//或者ac=(MainActivity) context;
    }
        //①定义回调接口
    public interface MyListener{
        public void sendContent(String info);
    }
}

在MainActivity中:

import com.example.wofu.aichi010.Fragment.FragmentOne.MyListener;//fragmentOne中的接口

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener,MyListener{
//fragmentOne中的接口,在这实现,以实现fragmentOne传值Mainactivity
    public void sendContent(String info) {
        if (info!=null && !"".equals(info)) {
            Log.e("sss",info);
        }else {
        }
    }
}

五、EventBus实现fragment向Activity传值

(待完成)

你可能感兴趣的:(2、Activity 与 Fragment 之间常见的几种通信方式)