fragment向fragment传递数据问题

fragment向fragment传递数据问题,我想从MsgFragment这里 点击之后获取城市名传到下一个跳转的AttractionsFragment并获取String city,我试过用javabean的SET GET方法没用。IndexFragment这个方法是写fragment跳转代码的。
有没有人帮下额。难住我很久了。
项目地址链接:https://pan.baidu.com/s/1VbWzHWg26cJ8iKNcIFlSeQ
提取码:vu86

public class IndexFragment extends Fragment implements ChangeFragment {

    private Fragment fragmentMsg;
    private Fragment fragmentColl;
    private Fragment fragmentAction;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View  view1 = LayoutInflater.from(getContext()).inflate(R.layout.fragment_index, container, false);
        return view1;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        fragmentMsg = MsgFragment.newInstance(this);
        fragmentColl = AttractionsFragment.newInstance(this);
        fragmentAction=AttractionsContentFragment.newInstance(this);

        changeResult();
    }

    @Override
    public void changeFragment() {
        getChildFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_content,fragmentColl).commit();
    }

    @Override
    public void changeResult() {
        getChildFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_content,fragmentMsg).commit();
    }

    @Override
    public void changeAttractionsContent() {
        getChildFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fl_content,fragmentAction).commit();
    }

}

public class MsgFragment extends Fragment {

    View view;

    private int i;
    private String str;


    private String[] mVals = new String[]{ "南宁市","柳州市","桂林市" ,"梧州市" ,"北海市","防城港市","钦州市","贵港市","玉林市","百色市","贺州市","河池市","来宾市","崇左市"};
    private LayoutInflater mInflater;
    private FlowLayout mFlowLayout;
    private CityEntity cityEntity ;




    private static ChangeFragment mChange;

    public static MsgFragment newInstance(ChangeFragment changeFragment) {
        mChange = changeFragment;
        Bundle args = new Bundle();
        MsgFragment fragment = new MsgFragment();
        fragment.setArguments(args);
        return fragment;
    }

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

        mInflater = LayoutInflater.from(getContext());


    }

    public MsgFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_msg, container, false);

        mFlowLayout = view.findViewById(R.id.id_flowlayout);


        initData();


        return view;
    }

    public void initData() {
        /**
         * 找到搜索标签的控件
         */
        for (i = 0; i < mVals.length; i++) {
            final TextView tv = (TextView) mInflater.inflate(
                    R.layout.search_label_tv, mFlowLayout, false);
            tv.setText(mVals[i]);
            str = tv.getText().toString();
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {

                        switch (((TextView) v).getText().toString()) {
                            case "南宁市":

                                String a="南宁市";



                                 changeToAnotherFragment();



                                break;
                            case "柳州市":
                                cityEntity.setCity("柳州市");
                                changeToAnotherFragment();

                                break;
                            case "桂林市":
                                cityEntity.setCity("桂林市");
                                changeToAnotherFragment();

                                break;
                            case "梧州市":
                                cityEntity.setCity("梧州市");
                                changeToAnotherFragment();

                                break;
                            case "北海市":
                                cityEntity.setCity("北海市");
                                changeToAnotherFragment();
                                break;
                            case "防城港市":
                                cityEntity.setCity("防城港市");
                                changeToAnotherFragment();
                                break;
                            case "钦州市":
                                cityEntity.setCity("钦州市");
                                changeToAnotherFragment();
                                break;
                            case "贵港市":
                                cityEntity.setCity("贵港市");
                                changeToAnotherFragment();
                                break;
                            case "玉林市":
                                cityEntity.setCity("玉林市");
                                changeToAnotherFragment();
                                break;
                            case "百色市":
                                cityEntity.setCity("百色市");
                                changeToAnotherFragment();
                                break;
                            case "贺州市":
                                cityEntity.setCity("贺州市");
                                changeToAnotherFragment();
                                break;
                            case "河池市":
                                cityEntity.setCity("河池市");
                                changeToAnotherFragment();
                                break;
                            case "来宾市":
                                cityEntity.setCity("来宾市");
                                changeToAnotherFragment();
                                break;
                            case "崇左市":
                                cityEntity.setCity("崇左市");
                                changeToAnotherFragment();
                                break;
                            default:

                                break;
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
            mFlowLayout.addView(tv);//添加到父View
        }


    }

    @SuppressLint("ResourceType")
    private void changeToAnotherFragment() {
        mChange.changeFragment();
    }
}

public class AttractionsFragment extends Fragment {
    private MyListView attr_lv;
    private JSONArray attr_array;
    private ImageLoaderConfiguration configuration;
    public DisplayImageOptions imageOptions;
    private Handler handler;
    private int msggg=0;
    public String city;

    private static ChangeFragment mChange;
    public static AttractionsFragment newInstance(ChangeFragment changeFragment) {
        mChange = changeFragment;
        Bundle args = new Bundle();

        AttractionsFragment fragment = new AttractionsFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //获取fragment的layout
        View  view = inflater.inflate(R.layout.fragment_attractions, container, false);
        //对recycleview进行配置





        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        attr_lv=view.findViewById(R.id.frag_attractions);
        configuration = ImageLoaderConfiguration.createDefault(getActivity());
        ImageLoader.getInstance().init(configuration);
        imageOptions = DisplayImageOptions.createSimple();
        initData();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what ==msggg){

                    attr_lv.setAdapter(new AttracListAdapter(getActivity()));
                    attr_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Toast.makeText(getActivity(),String.valueOf(position),Toast.LENGTH_SHORT).show();
                            try {
                                JSONObject object1=attr_array.getJSONObject(position);
                                String a= object1.getString("foodtitle");
                                String b=object1.getString("foodcontentimg");
                                System.out.println(a);
                                System.out.println(b);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    });

                }
            }
        };

    }






    private void initData() {
        new Thread(){
            public void run()
            {
                String url = DocUtil.attractions_list;





                System.out.println(city);
                OkHttpClient okHttpClient = new OkHttpClient();
                String token= CacheUtils.getString(getActivity(), "token", "");
                RequestBody body = new FormBody.Builder()
                        .add("token",token)
                        .add("city",city)
                        .build();

                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();

                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    //System.out.println(response.body().string());
                    try {
                        final String string=response.body().string();
                        final JSONObject object=new JSONObject(string);
                        attr_array=object.getJSONArray("attractionsList");
                        System.out.println(attr_array);
                        if(attr_array.length()>0) {

                            try {


                                Message msg = new Message();
                                msg.what = msggg;
                                handler.sendMessage(msg);


                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }else {
                            Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();





    }

    class AttracListAdapter extends BaseAdapter {
        private Context mContext;


        public AttracListAdapter(Context mContext) {
            super();
            this.mContext = mContext;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return attr_array.length();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        R.layout.attractions_item, parent, false);
                try {
                    JSONObject object=attr_array.getJSONObject(position);

                    TextView tvss1=convertView.findViewById(R.id.attrac_title);
                    TextView tvss2=convertView.findViewById(R.id.attrac_content);


                    tvss1.setText(object.getString("attractionstitle"));

                    tvss2.setText("地址:"+object.getString("attractionscontent"));

                    ImageView img=convertView.findViewById(R.id.attrac_img);



                    ImageLoader.getInstance().displayImage(DocUtil.base_url+
                                    object.getString("attrac_img"), img,
                            imageOptions);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            return convertView;
        }
    }
}

public interface ChangeFragment {

    void changeFragment();

    void changeResult();

    void changeAttractionsContent();
}

6个回答

使用腾讯的开源框架MMKV 完美解决问题

1 接口回调
2 MainActivity中定义 public static city,MsgFragment点击时赋值MainActiivty.city= AttractionsFragment中取值String city=MainActiivty.city
3 单例模式javabean
public class User {
private static User user;
private String city;

public String getCity() {
return city;
}

public void setCity(String city) {
    this.city = city;
}

public static User getInstance() {
if (user == null) {
synchronized (User.class) {
if (user == null) {
user = new User();
}
}
}
return user;
}
}
MsgFragment点击时User.getInstance.setCity(city),AttractionsFragment中取值String city=User.getInstance.getCity()

4 SharedPreferences存取
qq_34424362
qq_34424362 SharedPreferences 我已经用过了
7 个月之前 回复
qq_33451426
无fucker说 回复qq_34424362: 我都写得很明确了,MsgFragment点击时User.getInstance.setCity(city),city就是你AttractionsFragment中需要用到的值,然后在AttractionsFragment获取city就是User.getInstance.getCity(),先搞懂单列模式,要是还不会就没话说了
7 个月之前 回复
qq_34424362
qq_34424362 不能用,传不了
7 个月之前 回复
qq_34424362
qq_34424362 还是不懂,User.getInstance.setCity(city)是怎么用出来的
7 个月之前 回复
qq_33451426
无fucker说 回复qq_34424362: 是的 少写了个String
7 个月之前 回复
qq_33451426
无fucker说 回复qq_34424362: 不懂就百度下Android全局变量
7 个月之前 回复
qq_34424362
qq_34424362 这个能不能写得清楚一些,我不是很懂额。。。。
7 个月之前 回复
qq_34424362
qq_34424362 public static city是public static String city吗
7 个月之前 回复

推荐一个简单的传递,走一个单例,在第一个页面对单例进行赋值操作,放入你需要传的值,在第二个页面在从这个单例中取出这个数据值即可

sinat_33585352
MagicKim 回复qq_34424362: https://www.jianshu.com/p/f9ae5691e1bb 上面介绍了eventbus的使用,你可以看看,传递数据很方便的。
7 个月之前 回复
qq_34424362
qq_34424362 能贴下代码么。
7 个月之前 回复

eventbus用一下?

qq_34424362
qq_34424362 能贴下代码么。
7 个月之前 回复

图片说明图片说明
sk.csdn.net/upload/201903/28/1553762625_485285.png)

最简单的创建一个basefragment,分别让两个fragment继承,在basefragment里面创建一个用来存储数据的对象属性,在第一个存,第二个取就行。图片说明

public class BaseFragment extends Fragment {

List<String> list=new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_base, container, false);
}

}

dsxjinzhiqiang
dsxjinzhiqiang 回复qq_34424362: 用的是base里面的
7 个月之前 回复
qq_34424362
qq_34424362 我每个都声明List<String> list=new ArrayList<>();,并不能拿到信息。
7 个月之前 回复
qq_34424362
qq_34424362 你在first 和second两个fragment创建List<String> list=new ArrayList<>();这个了吗,为什么你没创建那边都有list的
7 个月之前 回复
dsxjinzhiqiang
dsxjinzhiqiang 回复qq_34424362: 给你截了个图和发了base的代码
7 个月之前 回复
qq_34424362
qq_34424362 能贴下代码么。
7 个月之前 回复

可以用intent发送一个广播撒。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!