qq_34424362 2019-03-28 11:53 采纳率: 50%
浏览 940
已采纳

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条回答 默认 最新

  • qq_34424362 2019-04-24 18:01
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题