android studio 在不同fragment之间发送数据如何实现

来源:互联网 发布:淘宝平铺拍摄布光 编辑:程序博客网 时间:2024/06/09 17:10

(黄色为替换后的右边的Fragment)

最近在学习android studio的fragement时遇到一个问题,在当前的2个fragment(LeftFragment(蓝色),RightFragment(红色))下面可以正常传送数据,单当切换至其他fragment传送数据时候就会出错,那该如何实现~~首先应该把fragment切换至当前RightFrame才可以~(因为我们需要测试是这个问题,不考虑在其他Fragment实现同样的代码),我们应该在代码里面判断当前的Fragment是否为RightFragment是的就直接发送信息,不是需要从新创建RightFrame,部分代码实现如下:

MainActivity里面代码

 if (getFragmentManager().findFragmentByTag("right")!=null)//此次是判断当前的fragment是否为RightFrament,其中tag=right需要在fragment_right.xml布局中定义        {            RightFragment rightFragment=(RightFragment)getFragmentManager().findFragmentById(R.id.frRight);//获取当前RightFragment对象            rightFragment.updateTextView(str);//此次为RightFragment对象里的一个更新新的方法        }        else        {
//如果当前不是RightFragment,就需要从新创建改对象,才能实现通信
            tvReceiveInfo.setVisibility(View.GONE);            RightFragment rightFragment1=new RightFragment();             FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();             Bundle bundle=new Bundle();//创建一个Bundle对象            bundle.putString("strData",str);//将传送的数据绑定至bundle            rightFragment1.setArguments(bundle);//将bundle绑定至RightFragment            fragmentTransaction.replace(R.id.frRight,rightFragment1);            fragmentTransaction.commit();        }

此处为RightFragment的代码

package fragment.tian.io.androidfrg;import android.content.Context;import android.net.Uri;import android.os.Bundle;import android.support.annotation.Nullable;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import android.app.Fragment;public class RightFragment extends Fragment {private TextView tvReceiveInfo;    public RightFragment() {        // Required empty public constructor    }   private String str1;    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Bundle bundle=getArguments();//这里接收bundle里面的数据,但是该数据需要在onAttach建立联系之前接受,不然会出错        if(bundle!=null) {            str1 = bundle.getString("strData");        }    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View view=inflater.inflate(R.layout.fragment_right, container, false);        tvReceiveInfo=(TextView)view.findViewById(R.id.tvReceiveInfo);        if (str1!=null)        {            tvReceiveInfo.setText(str1);//此处显示bundle传送的数据至Textview        }        return view;    }         public void updateTextView(String str)         {             tvReceiveInfo.setVisibility(View.VISIBLE);             tvReceiveInfo.setText(str);//此处是直接调用函数updateTextView显示传送数据         }}
至此就实现了切换了fragment时,实现Fragment的通信~~此处需要注意要在fragmeen布局文件里面加上tag标记做判断用~~

阅读全文
0 0
原创粉丝点击