Android中Activity和Fragment之间的通信

Android中Activity和Fragment之间的通信


  • Fragment启动Activity传数据到Fragment
    举例:城市选择列表。一个Fragment启动Activity,Activity再把城市选择数据回传到Fragment中。
Fragment中方法

   iv_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Toast.makeText(getActivity(), "点击了", Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getActivity(), CityActivity.class);
                startActivityForResult(intent,0);

            }
        });

重写onActivityResult方法

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("tag", "返回结果"+resultCode);
        // 取出intent中的值
        // 一般,加个null判断
        if (data != null) {
            String stringExtra = data.getStringExtra("city");
            cityid= data.getStringExtra("cityId");
            Log.d("tag", "城市ID"+cityid);
            getData(10);
            // 把取出的值设置到et_name中
            if (resultCode==1) {
                tv_city.setText(stringExtra);

            }
        }
    }
CityActivity

@Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final TextView textView = (TextView) holder.itemView;
            textView.setText(getItem(position).getCityName());//得到城市名
//            final String cityId = getItem(position).getCityId();//得到城市ID
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(CityActivity.this, "选择城市:"+textView.getText(), Toast.LENGTH_SHORT).show();
                   // Intent intent =new Intent();
                    Intent intent = getIntent();
                    intent.putExtra("city",textView.getText().toString());
                   //
                    for (int i = 0; i < cities.size(); i++) {
                        if (textView.getText().toString().equals(cities.get(i).getCityName())){
                            cityId = cities.get(i).getCityId();
                        }
                    }
                    intent.putExtra("cityId",cityId);
                    setResult(1,intent);
                    finish();
                }
            });
        }
  • Fragment传数据到Fragment
    举例:左边是电影列表的Fragment,右边是一个电影的具体内容的Fragment。点击左边的Fragment传数据给右边的Fragment显示。可以通过Fragment的fragment.setArguments(bundle)传。
MovieListFragment

@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        //当Item被点击,调用
        Toast.makeText(getActivity(), names[position]+":"+files[position], Toast.LENGTH_LONG).show();
        //点击时,获取Files数组对应的内容
        //把获取的内容传给Fragment  
        //加载对应的Fragment
        //5步骤

        MovieContentFragment fragment=new MovieContentFragment();
        //把传参传入到Fragment    
        Bundle bundle=new Bundle();
        bundle.putString("fileName", files[position]);
        fragment.setArguments(bundle);

        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.flayout, fragment);
        transaction.commit();

    }
MovieContentFragment

@Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // 取出参数
        Bundle bundle = getArguments();
        String name = bundle.getString("fileName");
        // 根据文件名,解析对应内容
  • Activity传数据到Fragment
    举例:新闻头部标签加载对应的Fragment. Activity通过传不同的url地址构建不同的Fragment。
Activity

/**
     * 初始化List<Fragment>
     */
    private void initFragment() {
        fragments = new ArrayList<>();
        //根据标题的个数,循环创建Fragment,
        int len = titles.length;
        for (int i = 0; i < len; i++) {
            //创建一个新的Fragment
            ContentFragment cf = new ContentFragment();
            //传入参数,以便构造不同的数据
            Bundle bundle = new Bundle();
            bundle.putString("key", urls[i]);
            cf.setArguments(bundle);
            //添加到Fragment集合中
            fragments.add(cf);
        }
    }
Fragment

//获取传入的参数,根据参数构造不同的数据
        Bundle bundle = getArguments();
        String values = bundle.getString("key");
        //异步任务
        MyTask myTask=new MyTask(new MyTask.CallBack() {
            @Override
            public void getData(List<NewsBean> list) {
                data.addAll(list);
                adapter.notifyDataSetChanged();
            }
        });
        myTask.execute(values);
posted @ 2016-10-06 11:03  程序IT猿  阅读(277)  评论(0编辑  收藏  举报